收發(fā)郵件(Mailing)

2018-02-24 15:40 更新

收發(fā)郵件

注意:本節(jié)正在開發(fā)中。

Yii 支持組成和發(fā)送電子郵件。然而,該框架提供的只有內(nèi)容組成功能和基本接口。實際的郵件發(fā)送機制可以通過擴展提供, 因為不同的項目可能需要不同的實現(xiàn)方式,它通常取決于外部服務和庫。

大多數(shù)情況下你可以使用?yii2-swiftmailer?官方擴展。

配置

郵件組件配置取決于你所使用的擴展。一般來說你的應用程序配置應如下:

return [
    //....
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
        ],
    ],
];

基本用法

一旦 “mailer” 組件被配置,可以使用下面的代碼來發(fā)送郵件:

Yii::$app->mailer->compose()
    ->setFrom('from@domain.com')
    ->setTo('to@domain.com')
    ->setSubject('Message subject')
    ->setTextBody('Plain text content')
    ->setHtmlBody('<b>HTML content</b>')
    ->send();

在上面的例子中所述的?compose()?方法創(chuàng)建了電子郵件消息,這是填充和發(fā)送的一個實例。 如果需要的話在這個過程中你可以用上更復雜的邏輯:

$message = Yii::$app->mailer->compose();
if (Yii::$app->user->isGuest) {
    $message->setFrom('from@domain.com')
} else {
    $message->setFrom(Yii::$app->user->identity->email)
}
$message->setTo(Yii::$app->params['adminEmail'])
    ->setSubject('Message subject')
    ->setTextBody('Plain text content')
    ->send();

注意:每個 “mailer” 的擴展也有兩個主要類別:“Mailer” 和 “Message”。 “Mailer” 總是知道類名和具體的 “Message”。 不要試圖直接實例 “Message” 對象 - 而是始終使用?compose()?方法。

你也可以一次發(fā)送幾封郵件:

$messages = [];
foreach ($users as $user) {
    $messages[] = Yii::$app->mailer->compose()
        // ...
        ->setTo($user->email);
}
Yii::$app->mailer->sendMultiple($messages);

一些特定的擴展可能會受益于這種方法,使用單一的網(wǎng)絡消息等。

撰寫郵件內(nèi)容

Yii 允許通過特殊的視圖文件來撰寫實際的郵件內(nèi)容。默認情況下,這些文件應該位于 “@app/mail” 路徑。

一個郵件視圖內(nèi)容的例子:

<?php
use yii\helpers\Html;
use yii\helpers\Url;

/* @var $this \yii\web\View view component instance */
/* @var $message \yii\mail\BaseMessage instance of newly created mail message */

?>
<h2>This message allows you to visit our site home page by one click</h2>
<?= Html::a('Go to home page', Url::home('http')) ?>

為了通過視圖文件撰寫正文可傳遞視圖名稱到?compose()?方法中:

Yii::$app->mailer->compose('home-link') // 渲染一個視圖作為郵件內(nèi)容
    ->setFrom('from@domain.com')
    ->setTo('to@domain.com')
    ->setSubject('Message subject')
    ->send();

你也可以在?compose()?方法中傳遞一些視圖所需參數(shù),這些參數(shù)可以在視圖文件中使用:

Yii::$app->mailer->compose('greetings', [
    'user' => Yii::$app->user->identity,
    'advertisement' => $adContent,
]);

你可以指定不同的視圖文件的 HTML 和純文本郵件內(nèi)容:

Yii::$app->mailer->compose([
    'html' => 'contact-html',
    'text' => 'contact-text',
]);

如果指定視圖名稱為純字符串,它的渲染結果將被用來作為 HTML Body,同時純文本正文將被刪除所有 HTML 實體。

視圖渲染結果可以被包裹進布局,可使用 yii\mail\BaseMailer::htmlLayout 和 yii\mail\BaseMailer::textLayout 來設置。 它的運行方式跟常規(guī)應用程序的布局是一樣的。布局可用于設置郵件 CSS 樣式或其他共享內(nèi)容:

<?php
use yii\helpers\Html;

/* @var $this \yii\web\View view component instance */
/* @var $message \yii\mail\MessageInterface the message being composed */
/* @var $content string main view render result */
?>
<?php $this->beginPage() ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=<?= Yii::$app->charset ?>" />
    <style type="text/css">
        .heading {...}
        .list {...}
        .footer {...}
    </style>
    <?php $this->head() ?>
</head>
<body>
    <?php $this->beginBody() ?>
    <?= $content ?>
    <div class="footer">With kind regards, <?= Yii::$app->name ?> team</div>
    <?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

文件附件

你可以使用?attach()?和?attachContent()?方法來添加附件的信息:

$message = Yii::$app->mailer->compose();

// 附件來自本地文件
$message->attach('/path/to/source/file.pdf');

// 動態(tài)創(chuàng)建一個文件附件
$message->attachContent('Attachment content', ['fileName' => 'attach.txt', 'contentType' => 'text/plain']);

嵌入圖片

你可以使用?embed()?方法將圖片插入到郵件內(nèi)容。此方法返回會圖片 ID ,這將用在 "img" 標簽中。 當通過視圖文件來寫信時,這種方法易于使用:

Yii::$app->mailer->compose('embed-email', ['imageFileName' => '/path/to/image.jpg'])
    // ...
    ->send();

然后在該視圖文件中,你可以使用下面的代碼:

<img src="https://atts.w3cschool.cn/attachments/image/cimg/2.0/<?= $message->embed($imageFileName); ?>">

測試和調試

開發(fā)人員常常要檢查一下,有什么電子郵件是由應用程序發(fā)送的,他們的內(nèi)容是什么等。這可通過yii\mail\BaseMailer::useFileTransport?來檢查。 如果開啟這個選項,會把郵件信息保存在本地文件而不是發(fā)送它們。這些文件保存在?yii\mail\BaseMailer::fileTransportPath?中,默認在 '@runtime/mail' 。

提示: 你可以保存這些信息到本地文件或者把它們發(fā)送出去,但不能同時兩者都做。

郵件信息文件可以在一個普通的文本編輯器中打開,這樣你就可以瀏覽實際的郵件標題,內(nèi)容等。這種機制可以用來調試應用程序或運行單元測試。

提示: 該郵件信息文件是會被?\yii\mail\MessageInterface::toString()?轉成字符串保存的,它依賴于實際在應用程序中使用的郵件擴展。

創(chuàng)建自己的郵件解決方案

為了創(chuàng)建你自己的郵件解決方案,你需要創(chuàng)建兩個類,一個用于 “Mailer”,另一個用于 “Message”。 你可以使用yii\mail\BaseMailer?和?yii\mail\BaseMessage?作為基類。這些類已經(jīng)實現(xiàn)了基本的邏輯,這在本指南中有介紹。 然而,它們的使用不是必須的,它實現(xiàn)了?yii\mail\MailerInterface?和?yii\mail\MessageInterface?接口。 然后,你需要實現(xiàn)所有 abstract 方法來構建解決方案。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號