我们需要查询数据库然后根据不同的数据动态生成pdf文件,然后把pdf文件作为附件形式发送
生成pdf使用yii2扩展mpdf具体详解参照官方http://www.yiiframework.com/extension/yii2-mpdf
安装
$ php composer.phar require kartik-v/yii2-mpdf"*"
配置
'components' => [ // setup Krajee Pdf component 'pdf' => [ 'class' => Pdf::classname(), 'format' => Pdf::FORMAT_A4, 'orientation' => Pdf::ORIENT_PORTRAIT, 'destination' => Pdf::DEST_BROWSER, // refer settings section for all configuration options ] ]
controller层
$mpdf = new mPDF('zh-CN'); $mpdf->useAdobeCJK = true; $data = ['name'=>'abc', 'age'=>12]; $mpdf->WriteHTML($this->renderPartial('templete', $data)); $new_file_name = time(); $tmp_save_path = \Yii::$app->basePath . '/tmp/' . $new_file_name . '.pdf'; $mpdf->Output($tmp_save_path, 'F');
templete模板(自定义html)
<div>名字<?=$name?></div> <div>年龄<?=$age?></div>
在配置文件main-local.php components=>[]里面配置
'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'useFileTransport' =>false,//这句一定有,false发送邮件,true只是生成邮件在runtime文件夹下,不发邮件 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'smtp.163.com', //每种邮箱的host配置不一样 'username' => '*******@163.com', 'password' => '*******', 'port' => '25', 'encryption' => 'tls', //加密这个看你的个人需要,若不需要加密有可能配置后导致邮件发送不出 ], 'messageConfig'=>[ 'charset'=>'UTF-8', 'from'=>['**********@163.com'=>'admin'] ], ],
controller层
$mail= Yii::$app->mailer->compose(); $mail->setTo('*****@**.com'); $mail->setSubject("subject"); $mail->setHtmlBody($this->renderPartial('templete')); //$mail->setTextBody('zheshisha '); $mail->attach('pdf1_path');//加入附件 $mail->attach('pdf2_path'); if($mail->send()) { return true; } return false;
templete模板(自定义html)
<div>这是一封重要邮件收到请回复</div>
2278total visits,1visits today
Leave a Reply