人気のPHP WEBアプリケーションフレームワークLaravelのTipsを記録していきます

Laravel で「テキストメール」「htmlメール」を送信する

● Laravel で 「テキストメール」をシンプルに送信する

// テキストメール送信
$from_email = "shop@test.server.com";
$from_name = "ショップ名";
$mail_subject = "ホームページからお問い合わせがありました。";
$mail_content = "メールの本文です\nテスト";
$to_email = "customer@user.com";
\Mail::send([], [], function($message) use ($from_email, $from_name, $mail_subject, $mail_content, $to_email ) {
    $message->from( $from_email, $from_name );
    $message->to( $to_email );
    $message->subject( $mail_subject );
    $message->setBody($mail_content);
});

● Laravel で 「htmlメール」をシンプルに送信する

// htmlメール送信
$from_email = "shop@test.server.com";
$from_name = "ショップ名";
$mail_subject = "ホームページからお問い合わせがありました。";
$mail_content = "<h1>メールの本文です</h1>";
$to_email = "customer@user.com";
\Mail::send([], [], function($message) use ($from_email, $from_name, $mail_subject, $mail_content, $to_email ) {
    $message->from( $from_email, $from_name );
    $message->to( $to_email );
    $message->subject( $mail_subject );
    $message->setBody($mail_content, 'text/html');
});

メール送信方式は .env の値を参照しに行きます sendmail を使って送信する場合の設定

MAIL_FROM_ADDRESS=test@user.com
MAIL_FROM_NAME=サイト名
MAIL_DRIVER=sendmail
MAIL_HOST=localhost

● Laravel で メールの設定を動的に変更する

.env の メール設定を取得するには config() を使用します

$mailconfig = config('mail');
dump( $mailconfig );

メール設定を動的に変更する

$mailconfig = [];
$mailconfig['driver']     = 1;
$mailconfig['host']       = 2;
$mailconfig['port']       = 3;
$mailconfig['username']   = 4;
$mailconfig['password']   = 5;
$mailconfig['encryption'] = null;

// メール設定の変更
$mailconfig = config(['mail' => $mailconfig ]);

● htmlメール送信のテストを行う

https://putsmail.com/tests/new

こちらからhtmlメール送信が行えます。

● htmlメールのサンプル

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="robots" content="noindex">
  <title>htmlメールのタイトル</title>
</head>
<body>

<h1>見出し1</h1>
<h2>見出し2</h2>
<h3>見出し3</h3>
<h4>見出し4</h4>
<h5>見出し5</h5>

<a href="https://www.google.co.jp/" target="_blank">GoogleのHP</a>

</body>
</html>
No.1496
05/21 10:37

edit