Yii框架需借助yii2-swiftmailer扩展实现邮件发送,配置mailer组件并设置SMTP参数,通过attach()或attachContent()添加附件,注意路径、编码及授权码等细节。
Yii 框架本身不直接提供邮件发送功能,需借助第三方扩展(如 yii2-swiftmailer)实现发邮件,包括带附件的邮件。以下是基于 Yii2 官方推荐方式的实用配置与发送方法。
在项目根目录执行:
composer require --prefer-dist yiisoft/yii2-swiftmailer
然后在 config/web.php 或 config/main.php 的 components 中添加配置:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@app/mail',
'useFileTransport' => false, // 设为 false 才真正发邮件
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com', // 如使用 QQ 邮箱则填 smtp.qq.com
'username' => 'your_email@gmail.com',
'password' => 'your_app_password', // 注意:Gmail 需用「应用专用密码」,QQ 邮箱需开启 SMTP 并获取授权码
'port' => 587,
'encryption' => 'tls',
],
],
附件可以是本地文件路径、临时文件或内存中的内容。关键点是使用 attach() 方法:
attachContent(),适合动态生成的 PDF、CSV 等示例代码:
$message = \Yii::$app->mailer->compose()
->setFrom(['admin@example.com' => '网站系统'])
->setTo('user@example.com')
->setSubject('您的订单附件')
->setTextBody('这是一封带附件的测试邮件')
->setHtmlBody('请查收附件:order.pdf
');
// 添加本地文件附件(绝对路径)
$message->attach('/path/to/order.pdf');
// 或添加内存中的 CSV 内容
$csvContent = "name,age\nAlice,25\nBob,30";
$message->attachContent($csvContent, [
'fileName' => 'data.csv',
'contentType' => 'text/csv',
]);
$message->send();
mb_convert_encoding() 转换,或改用英文名+中文描述'useFileTransport' => true 后邮件会保存在 @runtime/mail 目录,方便查看原始内容基本上就这些。只要配置正确、路径无误、权限到位,Yii 发带附件的邮件很稳定。不复杂但容易忽略细节,比如授权码、TLS 设置、绝对路径这些。