laravel 发送带附件的邮件

苏生不惑

有时候需要给运营定时发送表格数据,方式是定时跑程序将数据生成一个 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'));

clipboard.png

发送邮件

// 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
阅读 5.6k

技术分享
PHP,Python 相关
18.9k 声望
1.9k 粉丝
0 条评论
18.9k 声望
1.9k 粉丝
文章目录
宣传栏