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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles