yii2 邮件发送笔记

来源:互联网 发布:excel筛选两表重复数据 编辑:程序博客网 时间:2024/05/20 23:40

用什么学什么

这几天忙着收尾一个门户网站的外包,需要做一个点击即可发送邮件到指定邮箱的功能。琢磨了一下源代码,大致是这些步骤:

  • 在配置文件中设置好你用来发信的邮箱信息
  • 把邮件的发送和配置,写进Model类
  • 在Controller类的具体action方法中调用Model类
  • 在View文件中,使用 activeFormInstance>field(modelInstance,’attribute’); 来获取和 Model 相关的参数互动

改写配置文件

 YII2_ROOT/common/config/main-local.php中的 components/mailer/transport 配置块:

属性 值 host 邮件服务商网址,比如 smtp.163.com username 发信人用户名,必须和真实的邮件用户一致 password 发信邮箱密码 class 邮件服务的 php 类,一般是 Swift_SmtpTransport port 邮件服务端口,比如 25

注意

配置文件中的components/mailer/transport配置块,和 components/mailer 中的 useFileTransport 属性不能相互包含,请设useFileTransport为false

示例

完整的配置文件代码:

return [    'components' => [        'db' => [            'class' => 'yii\db\Connection',             'dsn' => 'mysql:host=localhost;dbname=我的数据库名', // 需要和服务器的 MySQL 用户和库名字一致            'username' => '我的数据库用户名',            'password' => '我的数据库密码',            'charset' => 'utf8',        ],        'mailer' => [            'class' => 'yii\swiftmailer\Mailer',            'viewPath' => '@common/mail',            // send all mails to a file by default. You have to set            // 'useFileTransport' to false and configure a transport            // for the mailer to send real emails.            'useFileTransport' => false,            'transport' => [                 'class' => 'Swift_SmtpTransport',                'host' => 'smtp.163.com', // 网易的 smtp 是能用的                'username' => '发信邮箱的用户名',                'password' => '发信邮箱的明文密码',                'port' => '25' // 不需要设置 tls 选项            ]         ],    ],];

使用邮件模板

假如你在 YII2_ROOT/backend/mail/layout里面放置了要调用的邮件模板demo.php ,那么位于 YII2_ROOT/backend/models 的 Model 类,需要使用\Yii::$app->mailer->compose('demo',['myParameter'=>'myValue']) ; 来确保使用使用了demo.php这个模板,第二个参数是配置给邮件模板(也是一种特殊的 View文件)的参数组成的一个数组。晚一点做好了项目,再更新这篇好了。

0 0
原创粉丝点击