イントロダクションIntroduction
Laravelは人気の高いSwiftMailerライブラリーのクリーンでシンプルなAPIを提供しています。SMTP、Mailgun、Mandrill、SparkPost、Amazon
SES、PHPのmail
機能、sendmail
ドライバーを提供しており、選択したローカルやクラウドベースのサービスを使い、素早くメール送信が開始できるようにしています。Laravel provides a clean, simple
API over the popular
SwiftMailer[http://swiftmailer.org] library.
Laravel provides drivers for SMTP, Mailgun,
Mandrill, SparkPost, Amazon SES, PHP's
mail
function, and
sendmail
, allowing you to quickly get
started sending mail through a local or cloud based
service of your choice.
ドライバの動作要件Driver Prerequisites
MailgunとMandrillなどAPIベースドライバはシンプルでSMTPサーバーよりも高速です。APIドライバは全てGuzzle
HTTPライブラリーをアプリケーションにインストールする必要があります。以下の行をcomposer.json
ファイルに追加し、Guzzle
5をプロジェクトに追加してください。The API based
drivers such as Mailgun and Mandrill are often
simpler and faster than SMTP servers. All of the API
drivers require that the Guzzle HTTP library be
installed for your application. You may install
Guzzle to your project by adding the following line
to your composer.json
file:
"guzzlehttp/guzzle": "~5.3|~6.0"
MailgunドライバMailgun Driver
Mailgunドライバを使用する場合、最初にGuzzleをインストールしてください。それからconfig/mail.php
設定ファイル中のdriver
オプションをmailgun
に設定してください。次にconfig/services.php
設定ファイルが以下のオプションを含んでいるか確認してください。To use the Mailgun driver, first
install Guzzle, then set the driver
option in your config/mail.php
configuration file to mailgun
. Next,
verify that your config/services.php
configuration file contains the following
options:
'mailgun' => [
'domain' => 'your-mailgun-domain',
'secret' => 'your-mailgun-key',
],
MandrillドライバMandrill Driver
Mandrillドライバを使用するには、最初にGuzzleをインストールし、次にconfig/mail.php
設定ファイル中のdriver
オプションをmandrill
に設定してください。それからconfig/services.php
設定ファイルに以下のオプションが含まれているか確認してください。To use the Mandrill driver, first
install Guzzle, then set the driver
option in your config/mail.php
configuration file to mandrill
. Next,
verify that your config/services.php
configuration file contains the following
options:
'mandrill' => [
'secret' => 'your-mandrill-key',
],
SparkPostドライバSparkPost Driver
SparkPostドライバを使用するには、最初にGuzzleをインストールし、次にconfig/mail.php
設定ファイル中のdriver
オプションをsparkpost
に設定してください。config/services.php
設定ファイルに以下のオプションが含まれているか確認してください。To use the SparkPost driver,
first install Guzzle, then set the
driver
option in your
config/mail.php
configuration file to
sparkpost
. Next, verify that your
config/services.php
configuration file
contains the following options:
'sparkpost' => [
'secret' => 'your-sparkpost-key',
],
SESドライバSES Driver
Amazon SESドライバを使う場合、Amazon AWS SDK for
PHPをインストールしてください。composer.json
ファイルのrequire
セクションに以下の行を追加し、このライブラリーをインストールします。To use the Amazon SES driver,
install the Amazon AWS SDK for PHP. You may install
this library by adding the following line to your
composer.json
file's
require
section:
"aws/aws-sdk-php": "~3.0"
次にconfig/mail.php
設定ファイルのdriver
オプションをses
に設定します。それからconfig/services
設定ファイルが以下の内容になっているか確認してください。Next, set the driver
option in your config/mail.php
configuration file to ses
. Then, verify
that your config/services.php
configuration file contains the following
options:
'ses' => [
'key' => 'your-ses-key',
'secret' => 'your-ses-secret',
'region' => 'ses-region', // e.g. us-east-1
],
メール送信Sending Mail
Laravelではメールのメッセージをビューとして保存します。たとえばメールを系統立てて利用するためにresources/views
ディレクトリにemails
ディレクトリを作成することができます。Laravel allows you to store your
e-mail messages in
views[/docs/{{version}}/views]. For example,
to organize your e-mails, you could create an
emails
directory within your
resources/views
directory:
メッセージを送るにはMail
ファサードのsend
メソッドを使います。send
メソッドは3つの引数を取ります。第1引数はメールの内容を含んでいるビューの名前です。第2引数はビューに渡すデータの配列です。第3引数はメッセージインスタンスを受け取る「クロージャ」のコールバックで、受信者や主題、もしくは他のメールの項目をカスタマイズできます。To send a message, use the
send
method on the Mail
facade[/docs/{{version}}/facades]. The
send
method accepts three arguments.
First, the name of a
view[/docs/{{version}}/views] that contains
the e-mail message. Secondly, an array of data you
wish to pass to the view. Lastly, a
Closure
callback which receives a
message instance, allowing you to customize the
recipients, subject, and other aspects of the mail
message:
<?php
namespace App\Http\Controllers;
use Mail;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* ユーザーにメールでリマインダーを送信
*
* @param Request $request
* @param int $id
* @return Response
*/
public function sendEmailReminder(Request $request, $id)
{
$user = User::findOrFail($id);
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
$m->from('hello@app.com', 'Your Application');
$m->to($user->email, $user->name)->subject('Your Reminder!');
});
}
}
上の例ではuser
キーを含んだ配列を渡していますので、以下のPHPコードにより、メールの中にユーザ名を挿入することができます。Since we are passing an array
containing the user
key in the example
above, we could display the user's name within our
e-mail view using the following PHP code:
<?php echo $user->name; ?>
注目:
$message
変数はいつもメールのビューに渡され、添付のインライン埋め込みが行えます。そのためビュー本体にmessage
変数を渡す必要はありません。Note: A$message
variable is always passed to e-mail views, and allows the inline embedding of attachments[#attachments]. So, you should avoid passing amessage
variable in your view payload.
メッセージの組み立てBuilding The Message
前述の通り、send
メソッドの第3引数は「クロージャ」で、メールの様々なオプションを指定できます。このクロージャを使用しCCやBCCなどメッセージの他の属性を指定することもできます。As previously discussed, the
third argument given to the send
method
is a Closure
allowing you to specify
various options on the e-mail message itself. Using
this Closure you may specify other attributes of the
message, such as carbon copies, blind carbon copies,
etc:
Mail::send('emails.welcome', $data, function ($message) {
$message->from('us@example.com', 'Laravel');
$message->to('foo@example.com')->cc('bar@example.com');
});
$message
メッセージビルダで使用できるメソッドの一覧です。Here is a list of the available
methods on the $message
message builder
instance:
$message->from($address, $name = null);
$message->sender($address, $name = null);
$message->to($address, $name = null);
$message->cc($address, $name = null);
$message->bcc($address, $name = null);
$message->replyTo($address, $name = null);
$message->subject($subject);
$message->priority($level);
$message->attach($pathToFile, array $options = []);
// $data文字列をそのまま付属ファイルへ
$message->attachData($data, $name, array $options = []);
// 裏で動作するSwiftMailerメッセージインスタンスの取得
$message->getSwiftMessage();
注目:
Mail::send
クロージャに渡されるメッセージインスタンスは、SwiftMailerメッセージクラスを拡張していますので、メールメッセージを構築するためにこのクラスのメソッドを呼び出すことができます。Note: The message instance passed to aMail::send
Closure extends the SwiftMailer message class, allowing you to call any method on that class to build your e-mail messages.
平文のメールMailing Plain Text
デフォルトでsend
メッソッドに指定するビューはHTMLで構成されているでしょう。しかしsend
メソッドの第1引数として配列を指定すると、HTMLビューに加えて平文テキストビューを指定できます。By default, the view given to the
send
method is assumed to contain HTML.
However, by passing an array as the first argument
to the send
method, you may specify a
plain text view to send in addition to the HTML
view:
Mail::send(['html.view', 'text.view'], $data, $callback);
もしくは平文テキストメールだけを送る必要があるなら、配列でtext
キーを指定することもできます。Or, if you only need to send a
plain text e-mail, you may specify this using the
text
key in the array:
Mail::send(['text' => 'view'], $data, $callback);
ロウ(raw)文字列Mailing Raw Strings
文字列を直接そのままメールしたい場合は、raw
メソッドを使ってください。You may use the raw
method if you wish to e-mail a raw string
directly:
Mail::raw('Text to e-mail', function ($message) {
//
});
添付Attachments
メールに添付する場合は、クロージャに渡される$message
オブジェクトのattach
メソッドを使用します。attach
メソッドでは最初の引数としてファイルの完全パスを指定します。To add attachments to an e-mail,
use the attach
method on the
$message
object passed to your Closure.
The attach
method accepts the full path
to the file as its first argument:
Mail::send('emails.welcome', $data, function ($message) {
//
$message->attach($pathToFile);
});
ファイルをメッセージ添付する場合、attach
メソッドの第2引数として配列を渡し、表示名やMIMEタイプを指定することもできます。When attaching files to a
message, you may also specify the display name and /
or MIME type by passing an array
as the
second argument to the attach
method:
$message->attach($pathToFile, ['as' => $display, 'mime' => $mime]);
attachData
メソッドははロウ文字列のバイトを添付するために使用します。たとえば、PDFをメモリ上で生成し、ディスクに書き出さすに添付したい場合に利用できます。The attachData
method may be used to attach a raw string of bytes
as an attachment. For example, you might use this
method if you have generated a PDF in memory and
want to attach it to the e-mail without writing it
to disk:
$message->attachData($pdf, 'invoice.pdf');
$message->attachData($pdf, 'invoice.pdf', ['mime' => $mime]);
インライン添付Inline Attachments
メールのビューに画像を埋め込むEmbedding An Image In An E-Mail View
メールに画像をインラインで埋め込むことは典型的な厄介事です。しかしLaravelは画像をメールに付け、最適なCIDを得る便利な方法を提供しています。インラインイメージを埋め込むには、メールビューの中で$message
変数のembed
メソッドを使ってください。Laravelは全メールビューで自動的に$message
変数を使用できるようにしていることを思い出してください。Embedding inline images into your
e-mails is typically cumbersome; however, Laravel
provides a convenient way to attach images to your
e-mails and retrieving the appropriate CID. To embed
an inline image, use the embed
method
on the $message
variable within your
e-mail view. Remember, Laravel automatically makes
the $message
variable available to all
of your e-mail views:
<body>
ここに画像:
<img src="<?php echo $message->embed($pathToFile); ?>">
</body>
メールのビューにロウ(raw)データーを埋め込むEmbedding Raw Data In An E-Mail View
メールメッセージへ埋め込む生データ文字列を既に用意してある場合は、$message
のembedData
メソッドを使ってください。If you already have a raw data
string you wish to embed into an e-mail message, you
may use the embedData
method on the
$message
variable:
<body>
ここにロウデータからの画像:
<img src="<?php echo $message->embedData($data, $name); ?>">
</body>
キュー使用メールQueueing Mail
メールメッセージのキューイングQueueing A Mail Message
メール送信はアプリケーションのレスポンスをとても遅くしてしまうため、多くの開発者はメールメッセージをバックグラウンドでキュー送信するようにしています。Laravelでは組み込みの共通キューAPIを使用することで、簡単に取り扱えるようになっています。メールメッセージをキューに投入するには、Mail
ファサードのqueue
メソッドを使用するだけです。Since sending e-mail messages can
drastically lengthen the response time of your
application, many developers choose to queue e-mail
messages for background sending. Laravel makes this
easy using its built-in unified queue
API[/docs/{{version}}/queues]. To queue a
mail message, use the queue
method on
the Mail
facade:
Mail::queue('emails.welcome', $data, function ($message) {
//
});
このメソッドはバックグラウンドでメールを送信するため、自動的にジョブをキューに投入する面倒を見ます。もちろんこの機能を使用する前にキューの設定を行う必要があります。This method will automatically take care of pushing a job onto the queue to send the mail message in the background. Of course, you will need to configure your queues[/docs/{{version}}/queues] before using this feature.
遅延メッセージキューDelayed Message Queueing
キューに投入したメールメッセージを送らせて配信したい場合はlater
メソッドを使用してください。メソッドの最初の引数として、メッセージ送信を遅らせたい秒数を指定するだけです。If you wish to delay the delivery
of a queued e-mail message, you may use the
later
method. To get started, simply
pass the number of seconds by which you wish to
delay the sending of the message as the first
argument to the method:
Mail::later(5, 'emails.welcome', $data, function ($message) {
//
});
特定のキューに投入Pushing To Specific Queues
メッセージを投入するキューを指定したい場合、queueOn
かlaterOn
メソッドを使用します。If you wish to specify a specific
queue on which to push the message, you may do so
using the queueOn
and
laterOn
methods:
Mail::queueOn('queue-name', 'emails.welcome', $data, function ($message) {
//
});
Mail::laterOn('queue-name', 5, 'emails.welcome', $data, function ($message) {
//
});
メールとローカル開発Mail & Local Development
メールを送信するアプリケーションを開発している間は、実際のメールアドレスにメールを送信したくはありません。Laravelはメールメッセージを実際に送信することを「無効」にする、様々な方法を用意しています。When developing an application that sends e-mail, you probably don't want to actually send e-mails to live e-mail addresses. Laravel provides several ways to "disable" the actual sending of e-mail messages.
LogドライバLog Driver
一つの解決方法は、ローカルでの開発期間中にlog
メールドライバを使用することです。このドライバは確認できるように全メールメッセージをログに書き込みます。環境ごとのアプリケーションの設定についての情報は、設定のドキュメントで確認してください。One solution is to use the
log
mail driver during local
development. This driver will write all e-mail
messages to your log files for inspection. For more
information on configuring your application per
environment, check out the configuration
documentation[/docs/{{version}}/installation#environment-configuration].
全メールの送信先指定Universal To
Laravelが提供するもう一つの解決策は、フレームワークが送信する全メールの共通受け取り先を設定する方法です。この方法を使うと送信メッセージに指定した実際のアドレスの代わりに、アプリケーションが送る全メールを特定のアドレスに送信します。この方法を使用する場合、config/mail.php
設定ファイルでto
オプションを指定します。Another solution provided by
Laravel is to set a universal recipient of all
e-mails sent by the framework. This way, all the
emails generated by your application will be sent to
a specific address, instead of the address actually
specified when sending the message. This can be done
via the to
option in your
config/mail.php
configuration
file:
'to' => [
'address' => 'dev@domain.com',
'name' => 'Dev Example'
],
MailtrapMailtrap
最後の方法はMailtrapのようなサービスを使い、smtp
ドライバで本当のメールクライアントにより内容を確認できる「ダミー」のメールボックスへメールメッセージを送る方法です。このアプローチの利点は最終的なメールをMailtrapのメッセージビュアーで実際に確認できることです。Finally, you may use a service
like Mailtrap[https://mailtrap.io] and the
smtp
driver to send your e-mail
messages to a "dummy" mailbox where you
may view them in a true e-mail client. This approach
has the benefit of allowing you to actually inspect
the final e-mails in Mailtrap's message
viewer.
イベントEvents
Laravelはメールメッセージを送信する直前に、イベントを発行します。このイベントは、メールが送られる場合に発行されますが、キューイングされる場合には発行されないことに留意してください。EventServiceProvider
へ、イベントリスナーを登録します。Laravel fires an event just
before sending mail messages. Remember, this event
is fired when the mail is sent, not when it
is queued. You may register an event listener in
your EventServiceProvider
:
/**
* アプリケーションへマッピングするイベントリスナー
*
* @var array
*/
protected $listen = [
'Illuminate\Mail\Events\MessageSending' => [
'App\Listeners\LogSentMessage',
],
];