简介
Laravel 的邮件功能基于热门的 SwiftMailer 函数库之上,提供了一个简洁的 API
Laravel为SMTP、Mailgun、Mandrill、Amazon、SES、PHP的mail函数、以及sendmail提供了驱动,可以非常方便灵活地使用Laravel来发送邮件
更多可参考Laravel邮件服务文档
那么Laravel如何使用SMTP来发送邮件呢? 往下看
配置
邮件的配置文件在config/mail.php文件中
我们只需要修改.env里的配置项即可
注: 需要先开启邮箱的SMTP邮件服务, 另QQ邮箱的SMTP密码是独立的, 并非邮箱密码
MAIL_DRIVER=smtp
MAIL_HOST=smtp.xx.com
MAIL_PORT=587
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
发信
首先需要先把Mail类use进来
use Illuminate\Support\Facades\Mail;
- 发送纯文本邮件$txt = '邮件文本'; $from = '发件人邮箱'; $name = 'Hoe'; $title = '邮件主题'; $to = '收件人'; Mail::raw($txt, function ($message) use ($from, $name, $title, $to) { $message->from($form, $name); $message->subject($title); $message->to($to); // 收件人邮箱 });
- 发送HTML模板邮件$data = ['name' => 'Hoe']; // 赋值到模板里的值 Mail::send('mail', $data, function ($message) use ($from, $name, $title, $to) { $message->from($from, $name); $message->subject($title); $message->to($to); // 收件人邮箱 });
- 在邮件中添加附件// 发送附件 Mail::send('mail', [], function ($message) use ($from, $name, $title, $to) { $message->from($from, $name); $message->subject($title); $message->to($to); // 收件人邮箱 $attachment = storage_path('xx.doc'); $message->attach($attachment, ['as'=>'xx.doc']); });
- 发送带图片的邮件除了发送附件之外,还可以发送带有图片的邮件 `$message`里的`embed`方法可以在邮件内容中插入图片 `$message`里的`embedData`方法可以将本地图片读取到内存然后渲染到邮件视图 $data = ['img' => 'https://www.anysgin.com/usr/themes/PureLoveForTypecho/images/banner2.jpg']; Mail::send('mail', $data, function ($message) use ($from, $name, $title, $to) { $message->from($from, $name); $message->subject($title); $message->to($to); // 收件人邮箱 }); // 模板里使用: <img src="{{ $message->embed($img) }}">
- 如果队列配置好了之后, 还可以使用队列的形式发信$data = ['name' => 'Hoe']; // 赋值到模板里的值 Mail::queue('mail', $data, function ($message) use ($from, $name, $title, $to) { $message->from($from, $name); $message->subject($title); $message->to($to); // 收件人邮箱 });
本文暂时没有评论,来添加一个吧(●'◡'●)