PHPプログラムに関する各種メモ書き

PHP の スタンダードなメール送信モジュール Swift_Mailer を使ってメールを送信する

● 1. メール送信方式(transport)を選んで作成する

(選択できるメール送信方式)

  • SMTPサーバを使う ( Swift_SmtpTransport )(おすすめ)
  • sendmailコマンドを使う ( Swift_SendmailTransport )

・1-1. SMTPサーバを使う

$SMTP_host = 'smtp.YOUR-SERVER.com';
$SMTP_port = '587';
$SMTP_option = 'tls';
$SMTP_user = '<メールアドレス>';
$SMTP_pass = '<メールパスワード>';	// Gmailの場合は2段階認証をon にしてアプリパスワードを設定します。

$transport = (new Swift_SmtpTransport($SMTP_host, $SMTP_port, $SMTP_option))
    ->setUsername($SMTP_user)
    ->setPassword($SMTP_pass);

・1-2. sendmailコマンドを使う

$transport = new Swift_SendmailTransport('/usr/sbin/sendmail -t');

● 2. メッセージを作成する

$mailer = new Swift_Mailer($transport);

$message = (new \Swift_Message('My important subject here'))
    ->setFrom([$from => $from_name])
    ->setTo( $to )
    ->setSubject( $subject )
    ->setBody( $mailtext);    // , 'text/html'

● 3. メッセージを送信する

$result = $mailer->send($message);
No.1629
11/27 11:06

edit