Table of Contents
1、简介
2、发送邮件
3、邮件&本地开发
4、 事件
Home Backend Development PHP Tutorial [ Laravel 5.2 文档 ] 服务 -- 邮件

[ Laravel 5.2 文档 ] 服务 -- 邮件

Jun 20, 2016 pm 12:37 PM

1、简介

Laravel基于  SwiftMailer库提供了一套干净清爽的邮件API。Laravel为SMTP、Mailgun、Mandrill、Amazon SES、PHP 的 mail函数,以及 sendmail提供了驱动,从而允许你快速通过本地或云服务发送邮件。

邮件驱动预备知识

基于驱动的 API 如Mailgun 和 Mandrill 通常比 SMTP 服务器更简单、更快。所有的 API 驱动要求应用已经安装 Guzzle HTTP 库。你可以通过添加如下行到 composer.json文件来安装 Guzzle 到项目:

"guzzlehttp/guzzle": "~5.3|~6.0"
Copy after login

Mailgun驱动

要使用 Mailgun 驱动(Mailgun 前10000封邮件免费,后续收费),首先安装 Guzzle,然后在配置文件 config/mail.php中设置 driver选项为 mailgun。接下来,验证配置文件 config/services.php包含如下选项:

'mailgun' => [    'domain' => 'your-mailgun-domain',    'secret' => 'your-mailgun-key',],
Copy after login

Mandrill驱动

要使用 Mandrill 驱动(Mandrill不支持中国区用户注册,汗!),首先安装 Guzzle,然后在配置文件 config/mail.php中设置 driver选项值为 mandrill。接下来,验证配置文件 config/services.php包含如下选项:

'mandrill' => [    'secret' => 'your-mandrill-key',],
Copy after login

SES驱动

要使用 Amazon SES 驱动(收费),安装 Amazon AWS 的 PHP SDK,你可以通过添加如下行到 composer.json文件的 require部分来安装该库:

"aws/aws-sdk-php": "~3.0"
Copy after login

接下来,设置配置文件 config/mail.php中的 driver选项为 ses。然后,验证配置文件 config/services.php包含如下选项:

'ses' => [    'key' => 'your-ses-key',    'secret' => 'your-ses-secret',    'region' => 'ses-region',  // e.g. us-east-1],
Copy after login

2、发送邮件

Laravel 允许你在视图中存储邮件信息,例如,要组织你的电子邮件,可以在 resources/views目录下创建 emails目录。

要发送一条信息,使用 Mail 门面上的 send方法。 send方法接收三个参数。第一个参数是包含邮件信息的视图名称;第二个参数是你想要传递到该视图的数组数据;第三个参数是接收消息实例的闭包回调——允许你自定义收件人、主题以及邮件其他方面的信息:

<?phpnamespace 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!');        });    }}
Copy after login

由于我们在上例中传递一个包含 user键的数组,我们可以在邮件中使用如下方式显示用户名:

<?php echo $user->name; ?>
Copy after login

注意: $message变量总是被传递到邮件视图,并允许嵌入附件,因此,你应该在视图负载中避免传入消息变量。

构造消息

正如前面所讨论的,传递给 send方法的第三个参数是一个允许你指定邮件消息本身多个选项的闭包。使用这个闭包可以指定消息的其他属性,例如抄送、群发,等等:

Mail::send('emails.welcome', $data, function ($message) {    $message->from('us@example.com', 'Laravel');    $message->to('foo@example.com')->cc('bar@example.com');});
Copy after login

下面试 $message消息构建器实例上的可用方法:

$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();
Copy after login

注意:传递给 Mail::send闭包的消息实例继承自 SwiftMailer消息类,该实例允许你调用该类上的任何方法来构建自己的电子邮件消息。

纯文本邮件

默认情况下,传递给 send方法的视图假定包含HTML,然而,通过传递数组作为第一个参数到 send方法,你可以指定发送除HTML视图之外的纯文本视图:

Mail::send(['html.view', 'text.view'], $data, $callback);
Copy after login

或者,如果你只需要发送纯文本邮件,可以指定在数组中使用text键:

Mail::send(['text' => 'view'], $data, $callback);
Copy after login

原生字符串邮件

如果你想要直接发送原生字符串邮件你可以使用 raw方法:

Mail::raw('Text to e-mail', function ($message) {    //});
Copy after login

2.1 附件

要添加附件到邮件,使用传递给闭包的 $message对象上的 attach方法。该方法接收文件的绝对路径作为第一个参数:

Mail::send('emails.welcome', $data, function ($message) {    //    $message->attach($pathToFile);});
Copy after login

当添加文件到消息时,你还可以通过传递数组作为第二个参数到 attach方法来指定文件显示名和MIME类型:

$message->attach($pathToFile, ['as' => $display, 'mime' => $mime]);
Copy after login

2.2 内联附件

在邮件视图中嵌入一张图片

嵌套内联图片到邮件中通常是很笨重的,然而,Laravel提供了一个便捷的方式附加图片到邮件并获取相应的CID,要嵌入内联图片,在邮件视图中使用 $message变量上的 embed方法。记住,Laravel自动在所有邮件视图中传入 $message变量使其有效:

<body>    Here is an image:    <img  src="<?php echo $message- alt="[ Laravel 5.2 文档 ] 服务 -- 邮件" >embed($pathToFile); ?>"></body>
Copy after login

在邮件视图中嵌入原生数据

如果你想要在邮件消息中嵌入原生数据字符串,可以使用 $message变量上的 embedData方法:

<body>    Here is an image from raw data:    <img  src="<?php echo $message- alt="[ Laravel 5.2 文档 ] 服务 -- 邮件" >embedData($data, $name); ?>"></body>
Copy after login

2.3 邮件队列

邮件消息队列

发送邮件消息可能会大幅度延长应用的响应时间,许多开发者选择将邮件发送放到队列中再后台执行,Laravel中可以使用内置的统一队列API来实现。要将邮件消息放到队列中,使用 Mail门面上的 queue方法:

Mail::queue('emails.welcome', $data, function ($message) {    //});
Copy after login

该方法自动将邮件任务推送到队列中以便在后台发送。当然,你需要在使用该特性前配置队列。

延迟消息队列

如果你想要延迟已经放到队列中邮件的发送,可以使用 later方法。只需要传递你想要延迟发送的秒数作为第一个参数到该方法即可:

Mail::later(5, 'emails.welcome', $data, function ($message) {    //});
Copy after login

推入指定队列

如果你想要将邮件消息推送到指定队列,可以使用 queueOn和 laterOn方法:

Mail::queueOn('queue-name', 'emails.welcome', $data, function ($message) {    //});Mail::laterOn('queue-name', 5, 'emails.welcome', $data, function ($message) {    //});
Copy after login

3、邮件&本地开发

开发发送邮件的应用时,你可能不想要真的发送邮件到有效的电子邮件地址,而只是想要做下测试。Laravel提供了几种方式“禁止”邮件的实际发送。

日志驱动

一种解决方案是在本地开发时使用 log邮件驱动。该驱动将所有邮件信息写到日志文件中以备查看,想要了解更多关于每个环境的应用配置信息,查看配置文档。

通用配置

Laravel提供的另一种解决方案是为框架发送的所有邮件设置通用收件人,这样的话,所有应用生成的邮件将会被发送到指定地址,而不是实际发送邮件指定的地址。这可以通过在配置文件 config/mail.php中设置 to选项来实现:

'to' => [    'address' => 'dev@domain.com',    'name' => 'Dev Example'],
Copy after login

Mailtrap

最后,你可以使用 Mailtrap服务和 smtp驱动发送邮件信息到“虚拟”邮箱,这种方法允许你在Mailtrap的消息查看器中查看最终的邮件。

4、 事件

Laravel 会发送邮件前触发一个事件,记住,这个事件是在邮件被发送时触发,而不是推送到队列时,你可以在 EventServiceProvider中注册事件监听器:

/** * The event listener mappings for the application. * * @var array */protected $listen = [    'Illuminate\Mail\Events\MessageSending' => [        'App\Listeners\LogSentMessage',    ],];
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles