ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] # 使用 邮件功能基于swiftMailer函数库之上,提供了简洁的API 配置config/mail.php ~~~ //支持这些驱动 Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill", | "ses", "sparkpost", "log" ~~~ 发件人的全局配置 ~~~ 'from'=>[ 'address'=>env('MAIL_FROM_ADDRESS','default'), 'name'=>env('MAIL_FROM_NAME','default'), ] ~~~ 在.env文件里面可以配置这些 ~~~ MAIL_DRIVER=smtp MAIL_HOST=smtp.163.com //邮件主机 MAIL_PORT=25 //端口 MAIL_USERNAME=15557105721@163.com MAIL_PASSWORD=xxx MAIL_ENCRYPTION=ssl //协议 ~~~ 然后在控制器写个方法 ~~~ public function mail() { //use Mail; Mail::raw('邮件内容-测试',function($message) { //第一个形参邮件内容 $message->from('15557105721@163.com','jdxia'); //1是发件人 2名字 $message->subject('邮件主题-测试'); //邮件主题 $message->to('825455423@qq.com'); //发送给谁 }); } ~~~ # 发送带附件的邮件 有时候需要给运营定时发送表格数据,方式是定时跑程序将数据生成一个 excel 然后邮件发送到运营邮箱,这里用 laravel 来处理. 安装 maatwebsite/excel ~~~ composer reuqire maatwebsite/excel ~~~ 下载 excel ~~~ $titles = [ '用户ID', '用户昵称', '公司名称', '销售', '功能版本', '次数', '最高', '消耗', '剩余', '时间' ]; //使用 Excel::create $data_arr=[$titles,['user_id'=>100,'nick_name'=>'xxx','company'=>'百度','seller_name'=>'老王','user_type'=>1,'times'=>666,'top'=>100,'flows'=>88,'rest'=>123,'time'=>date('YmdHis')]];//从数据库读取的结果 //http://www.maatwebsite.nl/laravel-excel/docs/export \Excel::create('excel', function($excel) use($data_arr){ $excel->sheet('Sheetname', function($sheet) use($data_arr) { $sheet->fromArray($data_arr, null, 'A1', false, false); }); })->store('xlsx',storage_path('excel/exports')); ~~~ 发送邮件 ~~~ // https://docs.golaravel.com/docs/5.0/mail/ 邮件配置参考 #cat .env MAIL_DRIVER=smtp MAIL_HOST=smtp.exmail.qq.com MAIL_PORT=25 MAIL_USERNAME=xxx@xxx.com MAIL_PASSWORD=xxx #cat config/mail.php //模板文件 #cat resources/views/emails/attachment.balde.php 附件内容:{{$content}} <br> 发送时间:{{date('Y-m-d H:i:s')}} //重试 3次 $tryTimes=3; do { $email='xxx@xx.com'; $attachments=['file'=>storage_path('excel/exports').'/excel.xlsx'];//上面下载的 excel 附件 $subject='mail'; $cc='xxx@xx.com';//抄送邮件 $sendResult = \Mail::send('emails.attachment', ['content' => '发送内容'], function ($message) use ($email, $attachments, $subject, $cc) { $message->to($email)->subject($subject); foreach ($attachments as $alias => $attachment) { $ext = pathinfo($attachment)['extension']; $message->attach($attachment, ['as' => "=?UTF-8?B?" . base64_encode($alias) . "?=." . $ext]);// } if (!empty($cc)) { $message->cc($cc); } }); $tryTimes--; } while ($sendResult == 0 && $tryTimes); dd($sendResult);//发送成功 2 ~~~