使用 Laravel 基于 SMTP 驅(qū)動實現(xiàn)發(fā)送郵件

環(huán)境

  • PHP 7
  • Laravel 5.1
  • OS X El Capitan 10.11.4

簡介

Laravel 基于熱門的 SwiftMailer 函數(shù)庫提供了一個簡潔的 API。Laravel 為 SMTP、Mailgun拼卵、Mandrill备燃、Amazon SES、PHP 的 mail 函數(shù)及 sendmail 提供驅(qū)動猛拴,讓你可以快速地從所選擇的本地或云端服務(wù)開始發(fā)送郵件。(摘錄 PHPhub 翻譯文檔)

配置

郵件配置文件是config/mail.php

return [
    // 默認(rèn)發(fā)送郵件驅(qū)動
    'driver' => env('MAIL_DRIVER', 'smtp'),

    // 發(fā)送郵件主機地址
    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    // 發(fā)送郵件主機端口
    'port' => env('MAIL_PORT', 587),

    // 指定發(fā)送郵件的郵箱地址和用戶名稱
    'from' => ['address' => null, 'name' => null],

    // 指定發(fā)送郵件協(xié)議
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    // 郵箱登錄賬號
    'username' => env('MAIL_USERNAME'),

    // 郵箱登錄密碼
    'password' => env('MAIL_PASSWORD'),

    // 當(dāng)驅(qū)動為 sendmail 時,指定驅(qū)動的命令地址
    'sendmail' => '/usr/sbin/sendmail -bs',

    // false 發(fā)送郵件不記錄日志耐朴,true 記錄日志不發(fā)送郵件
    'pretend' => false,
];

編寫發(fā)送文字郵件程序

env

本文采用 QQ 郵箱進行測試,首先修改郵箱配置

MAIL_DRIVER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=465
MAIL_USERNAME=(填寫 QQ 郵箱賬號)
MAIL_PASSWORD=(填寫 QQ 郵箱密碼)
MAIL_ENCRYPTION=ssl

路由

/* 發(fā)送文字郵件 */
Route::get('email/send/{id}', [
    'as'   => 'backend.email.send',
    'uses' => 'EmailController@send',
]);

控制器

新增控制器

php artisan make:controller Backend/EmailController --plain

控制器代碼如下

<?php

namespace App\Http\Controllers\Backend;

use App\Facades\UserRepository;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Mail;

class EmailController extends Controller
{
    public function send(Request $request, $id)
    {
        $user = UserRepository::find($id);

        Mail::send('emails.test', ['user' => $user], function ($email) use ($user) {
            $email->to('2794408425@qq.com')->subject('Hello World');
        });
    }
}

視圖

新增視圖emails/test.blade.php盹憎,代碼如下:

<html>
    <head>
        <title></title>
    </head>
    <body>
        你好,{{$user->name}},這是一封測試郵件筛峭。
    </body>
</html>

執(zhí)行代碼

在瀏覽器訪問指定路由,然后去郵箱查看郵件是否發(fā)送成功陪每。


發(fā)送文字郵件

編寫發(fā)送圖文郵件程序

路由

Route::get('email/sendPicture/{id}', [
    'as'   => 'backend.email.sendPicture',
    'uses' => 'EmailController@sendPicture',
]);

控制器

public function sendPicture(Request $request, $id)
{
    $user = UserRepository::find($id);
    $icon = "http://o93kt6djh.bkt.clouddn.com/Laravel-SendEmaillaravel-200x50.png";
    $image = "http://o93kt6djh.bkt.clouddn.com/Laravel-SendEmaillaravel-600x300.jpg";

    Mail::send('emails.image', ['name' => $user->name, 'icon' => $icon, 'image' => $image], function ($email) {
        $someOne = '2794408425@qq.com';
        $email->to($someOne)->subject('圖文郵件標(biāo)題');
    });

    echo "已發(fā)送郵件,請注意查收";
}

視圖

新增視圖emails/image.blade.php影晓,代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="viewport" content="width=device-width"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>CowCat Email Test</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        * {
            font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif;
        }

        img {
            max-width: 100%;
        }

        .collapse {
            margin: 0;
            padding: 0;
        }

        body {
            -webkit-font-smoothing: antialiased;
            -webkit-text-size-adjust: none;
            width: 100% !important;
            height: 100%;
        }

        /* -------------------------------------
                ELEMENTS
        ------------------------------------- */
        a {
            color: #2BA6CB;
        }

        .btn {
            text-decoration: none;
            color: #FFF;
            background-color: #666;
            padding: 10px 16px;
            font-weight: bold;
            margin-right: 10px;
            text-align: center;
            cursor: pointer;
            display: inline-block;
        }

        p.callout {
            padding: 15px;
            background-color: #ECF8FF;
            margin-bottom: 15px;
        }

        .callout a {
            font-weight: bold;
            color: #2BA6CB;
        }

        table.social {
            /*  padding:15px; */
            background-color: #ebebeb;

        }

        .social .soc-btn {
            padding: 3px 7px;
            font-size: 12px;
            margin-bottom: 10px;
            text-decoration: none;
            color: #FFF;
            font-weight: bold;
            display: block;
            text-align: center;
        }

        a.fb {
            background-color: #3B5998 !important;
        }

        a.tw {
            background-color: #1daced !important;
        }

        a.gp {
            background-color: #DB4A39 !important;
        }

        a.ms {
            background-color: #000 !important;
        }

        .sidebar .soc-btn {
            display: block;
            width: 100%;
        }

        /* -------------------------------------
                HEADER
        ------------------------------------- */
        table.head-wrap {
            width: 100%;
        }

        .header.container table td.logo {
            padding: 15px;
        }

        .header.container table td.label {
            padding: 15px;
            padding-left: 0px;
        }

        /* -------------------------------------
                BODY
        ------------------------------------- */
        table.body-wrap {
            width: 100%;
        }

        /* -------------------------------------
                FOOTER
        ------------------------------------- */
        table.footer-wrap {
            width: 100%;
            clear: both !important;
        }

        .footer-wrap .container td.content p {
            border-top: 1px solid rgb(215, 215, 215);
            padding-top: 15px;
        }

        .footer-wrap .container td.content p {
            font-size: 10px;
            font-weight: bold;

        }

        /* -------------------------------------
                TYPOGRAPHY
        ------------------------------------- */
        h1, h2, h3, h4, h5, h6 {
            font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
            line-height: 1.1;
            margin-bottom: 15px;
            color: #000;
        }

        h1 small, h2 small, h3 small, h4 small, h5 small, h6 small {
            font-size: 60%;
            color: #6f6f6f;
            line-height: 0;
            text-transform: none;
        }

        h1 {
            font-weight: 200;
            font-size: 44px;
        }

        h2 {
            font-weight: 200;
            font-size: 37px;
        }

        h3 {
            font-weight: 500;
            font-size: 27px;
        }

        h4 {
            font-weight: 500;
            font-size: 23px;
        }

        h5 {
            font-weight: 900;
            font-size: 17px;
        }

        h6 {
            font-weight: 900;
            font-size: 14px;
            text-transform: uppercase;
            color: #444;
        }

        .collapse {
            margin: 0 !important;
        }

        p, ul {
            margin-bottom: 10px;
            font-weight: normal;
            font-size: 14px;
            line-height: 1.6;
        }

        p.lead {
            font-size: 17px;
        }

        p.last {
            margin-bottom: 0px;
        }

        ul li {
            margin-left: 5px;
            list-style-position: inside;
        }

        /* -------------------------------------
                SIDEBAR
        ------------------------------------- */
        ul.sidebar {
            background: #ebebeb;
            display: block;
            list-style-type: none;
        }

        ul.sidebar li {
            display: block;
            margin: 0;
        }

        ul.sidebar li a {
            text-decoration: none;
            color: #666;
            padding: 10px 16px;
            /*  font-weight:bold; */
            margin-right: 10px;
            /*  text-align:center; */
            cursor: pointer;
            border-bottom: 1px solid #777777;
            border-top: 1px solid #FFFFFF;
            display: block;
            margin: 0;
        }

        ul.sidebar li a.last {
            border-bottom-width: 0px;
        }

        ul.sidebar li a h1, ul.sidebar li a h2, ul.sidebar li a h3, ul.sidebar li a h4, ul.sidebar li a h5, ul.sidebar li a h6, ul.sidebar li a p {
            margin-bottom: 0 !important;
        }

        /* ---------------------------------------------------
                RESPONSIVENESS
                Nuke it from orbit. It's the only way to be sure.
        ------------------------------------------------------ */

        /* Set a max-width, and make it display as block so it will automatically stretch to that width, but will also shrink down on a phone or something */
        .container {
            display: block !important;
            max-width: 600px !important;
            margin: 0 auto !important; /* makes it centered */
            clear: both !important;
        }

        /* This should also be a block element, so that it will fill 100% of the .container */
        .content {
            padding: 15px;
            max-width: 600px;
            margin: 0 auto;
            display: block;
        }

        /* Let's make sure tables in the content area are 100% wide */
        .content table {
            width: 100%;
        }

        /* Odds and ends */
        .column {
            width: 300px;
            float: left;
        }

        .column tr td {
            padding: 15px;
        }

        .column-wrap {
            padding: 0 !important;
            margin: 0 auto;
            max-width: 600px !important;
        }

        .column table {
            width: 100%;
        }

        .social .column {
            width: 280px;
            min-width: 279px;
            float: left;
        }

        /* Be sure to place a .clear element after each set of columns, just to be safe */
        .clear {
            display: block;
            clear: both;
        }

        /* -------------------------------------------
                PHONE
                For clients that support media queries.
                Nothing fancy.
        -------------------------------------------- */
        @media only screen and (max-width: 600px) {

            a[class="btn"] {
                display: block !important;
                margin-bottom: 10px !important;
                background-image: none !important;
                margin-right: 0 !important;
            }

            div[class="column"] {
                width: auto !important;
                float: none !important;
            }

            table.social div[class="column"] {
                width: auto !important;
            }

        }
    </style>
</head>

<body bgcolor="#FFFFFF">

<!-- HEADER -->
<table class="head-wrap" bgcolor="#999999">
    <tr>
        <td></td>
        <td class="header container">

            <div class="content">
                <table bgcolor="#999999">
                    <tr>
                        <td>[站外圖片上傳中……(4)]</td>
                        <td align="right"><h6 class="collapse">Test</h6></td>
                    </tr>
                </table>
            </div>

        </td>
        <td></td>
    </tr>
</table><!-- /HEADER -->


<!-- BODY -->
<table class="body-wrap">
    <tr>
        <td></td>
        <td class="container" bgcolor="#FFFFFF">

            <div class="content">
                <table>
                    <tr>
                        <td>

                            <h3>Welcome, {{$name}}</h3>
                            <p class="lead">This is a Test Email of the CowCat</p>

                            <!-- A Real Hero (and a real human being) -->
                            <p>[站外圖片上傳中……(5)]</p><!-- /hero -->

                            <!-- Callout Panel -->
                            <p class="callout">
                                Laravel is the best PHP Framework
                                <a >Learn it Now! &raquo;</a>
                            </p><!-- /Callout Panel -->

                            <h3>Hello
                                <small>World</small>
                            </h3>
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                                exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
                                dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
                                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
                                mollit anim id est laborum.</p>
                            <a class="btn">Click Me!</a>

                            <br/>
                            <br/>

                            <!-- social & contact -->
                            <table class="social" width="100%">
                                <tr>
                                    <td>

                                        <!--- column 1 -->
                                        <table align="left" class="column">
                                            <tr>
                                                <td>

                                                    <h5 class="">Connect with Us:</h5>
                                                    <p class=""><a href="#" class="soc-btn fb">Facebook</a>
                                                        <a href="#" class="soc-btn tw">Twitter</a>
                                                        <a href="#" class="soc-btn gp">Google+</a></p>


                                                </td>
                                            </tr>
                                        </table><!-- /column 1 -->

                                        <!--- column 2 -->
                                        <table align="left" class="column">
                                            <tr>
                                                <td>

                                                    <h5 class="">Contact Info:</h5>
                                                    <p>Phone: <strong>408.341.0600</strong><br/>
                                                        Email:
                                                        <strong><a href="emailto:hseldon@trantor.com">hseldon@trantor
                                                                .com</a></strong></p>

                                                </td>
                                            </tr>
                                        </table><!-- /column 2 -->

                                        <span class="clear"></span>

                                    </td>
                                </tr>
                            </table><!-- /social & contact -->


                        </td>
                    </tr>
                </table>
            </div>

        </td>
        <td></td>
    </tr>
</table><!-- /BODY -->

<!-- FOOTER -->
<table class="footer-wrap">
    <tr>
        <td></td>
        <td class="container">

            <!-- content -->
            <div class="content">
                <table>
                    <tr>
                        <td align="center">
                            <p>
                                <a href="#">Terms</a> |
                                <a href="#">Privacy</a> |
                                <a href="#">
                                    <unsubscribe>Unsubscribe</unsubscribe>
                                </a>
                            </p>
                        </td>
                    </tr>
                </table>
            </div><!-- /content -->

        </td>
        <td></td>
    </tr>
</table><!-- /FOOTER -->

</body>
</html>

執(zhí)行代碼

在瀏覽器訪問指定路由镰吵,然后去郵箱查看郵件是否發(fā)送成功。


發(fā)送圖文郵件

編寫發(fā)送附件郵件程序

路由

Route::get('email/sendFile/{id}', [
    'as'   => 'backend.email.sendFile',
    'uses' => 'EmailController@sendFile',
]);

控制器

public function sendFile(Request $request, $id)
{
    $user = UserRepository::find($id);
    $icon = "http://o93kt6djh.bkt.clouddn.com/Laravel-SendEmaillaravel-200x50.png";

    Mail::send('emails.test-file', ['name' => $user->name, 'icon' => $icon], function ($message) {
        $someOne = "2794408425@qq.com";
        $file = storage_path("app/PHP7介紹和應(yīng)用實踐.pdf");
        $message->to($someOne)->subject("附件郵件標(biāo)題");
        $message->attach($file, ['as' => 'PHP7 Introduction and Application Action.pdf', 'mime' => 'application/pdf']);
    });


    echo '已發(fā)送郵件,請注意查收';
}

視圖

新增視圖emails/test-file.blade.php挂签,代碼如下:

<html>
    <head>
        <title></title>
    </head>
    <body>
        <p>
            你好,{{$name}},這是一封測試郵件疤祭。
            下面將會顯示一張原始數(shù)據(jù)圖片
        </p>
        <p>
            <img src="{{$message->embed($icon)}}" alt="原始數(shù)據(jù)圖片">
        </p>
    </body>
</html>

執(zhí)行代碼

在瀏覽器訪問指定路由,然后去郵箱查看郵件是否發(fā)送成功饵婆。


發(fā)送附件郵件
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末勺馆,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子啦辐,更是在濱河造成了極大的恐慌谓传,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件芹关,死亡現(xiàn)場離奇詭異续挟,居然都是意外死亡,警方通過查閱死者的電腦和手機侥衬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進店門诗祸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人轴总,你說我怎么就攤上這事直颅。” “怎么了怀樟?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵功偿,是天一觀的道長。 經(jīng)常有香客問我往堡,道長械荷,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任虑灰,我火速辦了婚禮吨瞎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘穆咐。我一直安慰自己颤诀,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布对湃。 她就那樣靜靜地躺著崖叫,像睡著了一般。 火紅的嫁衣襯著肌膚如雪熟尉。 梳的紋絲不亂的頭發(fā)上归露,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天,我揣著相機與錄音斤儿,去河邊找鬼剧包。 笑死,一個胖子當(dāng)著我的面吹牛往果,可吹牛的內(nèi)容都是我干的疆液。 我是一名探鬼主播,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼陕贮,長吁一口氣:“原來是場噩夢啊……” “哼堕油!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起肮之,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤掉缺,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后戈擒,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體眶明,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年筐高,在試婚紗的時候發(fā)現(xiàn)自己被綠了搜囱。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,444評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡柑土,死狀恐怖蜀肘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情稽屏,我是刑警寧澤扮宠,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站狐榔,受9級特大地震影響坛增,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜荒叼,卻給世界環(huán)境...
    茶點故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一轿偎、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧被廓,春花似錦坏晦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蜓斧,卻和暖如春仓蛆,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背挎春。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工看疙, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留豆拨,地道東北人。 一個月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓能庆,卻偏偏與公主長得像施禾,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子搁胆,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容