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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值