laravel发送邮件并配置发件人信息
最近要做发送邮件的功能,发送邮件的功能还是比较简单的,可以使用 PHPMailer 包。
$mail = new PHPMailer\PHPMailer();
try {
$mail->addaddress('username@mail.com');
$mail->CharSet = 'UTF-8';
$mail->From = 'admin@mail.com';
$mail->FromName = "ADMIN";
$mail->isHTML(true);
$mail->Subject = 'mail测试';
$html = <<<html
<h4 style="color: red">邮件测试</h4>
<table border="1px">
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
html;
$mail->Body = $html;
$mail->send();
} catch (\PHPMailer\Exception $e) {
print_r($e->getMessage());
}
然 php 框架使用 laravel5.7 ,还是使用 laravel 中的发邮件功能,查阅了 laravel 关于 mail 的文档,还是比较简单的。
//.env文件配置
MAIL_MAILER=smtp
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=
根据实际使用的发件邮箱配置,后两项可不配置。
#生成可邮寄类
php artisan make:mail OrderShipped
修改可邮寄类
namespace App\Mail;
use App\Model\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class OrderShipped extends Mailable
{
use Queueable, SerializesModels;
/**
* 订单实例.
*
* @var Order
*/
public $order;
/**
* 创建一个新的消息实例.
*
* @return void
*/
public function __construct(Order $order)
{
$this->order = $order;
}
/**
* 构建消息.
*
* @return $this
*/
public function build()
{
return $this->from('example@example.com')
->subject('subject')
->view('emails.orders.shipped')
->attach('/path/to/file')
->attach('/path/to/file', [
'as' => 'name.pdf',
'mime' => 'application/pdf',
]);;
}
}
resources/views/emails/order/shiped.blade.php
<div>
Price: {{ $order->price }}
</div>
发邮件
#发邮件
use Illuminate\Support\Facades\Mail;
Mail::to('email_address')
->send(new OrderShipped($order));
成功发送邮件了。
然后需求要求发件人的名字不要用 example,要用 Example。继续搜索文档,配置发件人,发现可以用全局的配置,在配置文件 config/mail.php下配置:
'from' => ['address' => 'example@example.com', 'name' => 'Example'],
配置完成,收到的邮件发件人的名字依然是 example,而不是 Example,配置未生效。
查看 Mail 门面类的源码,发现了还有这几种写法:
@method static void raw(string $text, $callback)
@method static void plain(string $view, array $data, $callback)
@method static void html(string $html, $callback)
@method static void send(\Illuminate\Contracts\Mail\Mailable|string|array $view, array $data = [], \Closure|string $callback = null)
修改如下:
use Illuminate\Support\Facades\Mail;
function sendMail($template, $info, $to_addr, $from_addr = 'example@example.com', $from_name = 'Example', $subject = '测试')
{
Mail::send($template, ['info' => $info], function ($message) use ($to_addr, $from_addr, $from_name, $subject) {
$message->from($from_addr, $from_name);
$message->to($to_addr);
$message->subject($subject);
});
}
可以灵活的设置发件地址,发件人名称,邮件标题,完美的满足了需求。
浙公网安备 33010602011771号