最近要做发送邮件的功能,发送邮件的功能还是比较简单的,可以使用PHPMailer包
<?php $mail = new PHPMailer\PHPMailer(); try { $mail->addaddress('[email protected]'); $mail->CharSet = 'UTF-8'; $mail->From = '[email protected]'; $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
#修改可邮寄类 <?php 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('[email protected]') ->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>
#发邮件 <?php use Illuminate\Support\Facades\Mail; Mail::to('email_address') ->send(new OrderShipped($order));
成功发送邮件了,然后需求要求发件人的名字不要用example,要用Example。继续搜索文档,配置发件人,发现可以用全局的配置,在配置文件 config/mail.php下配置
'from' => ['address' => '[email protected]', 'name' => 'Example'],
配置完成,收到的邮件发件人的名字依然是example,而不是Example,配置未生效
在Laravel之邮件发送 (huati365.com) 这篇文章中 看到了这么一种写法,查看了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)
<?php use Illuminate\Support\Facades\Mail; function sendMail($template, $info, $to_addr, $from_addr = '[email protected]', $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); }); }
可以灵活的设置发件地址,发件人名称,邮件标题,完美的满足了需求。
标签:laravel,发件人,MAIL,mail,example,邮件,subject From: https://www.cnblogs.com/caroline2016/p/16986943.html