一、 下载swiftMailer 可以从github下载 https://github.com/swiftmailer/swiftmailer
二、 解压安装包 引入
require_once'swiftmailer-5.4.8\lib\swift_required.php';
三、获取传输对象 设置stmp服务器地址,用户名 密码(密码为授权码)
$transport= Swift_SmtpTransport::newInstance('smtp.163.com',25,null);
$transport->setUsername('XXXXXX@163.com');
$transport->setPassword('qwer1234');
四、 实例化发送邮件对象
$mailer= Swift_Mailer::newInstance($transport);
五、实例化邮件信息对象 设置发送的主题 内容 字符集 接收对象 发送对象等
$message = Swift_Message::newInstance();
$message->setTo(['xxxxx.@qq.com' => ['接收人']]); //邮件接收对象
$message->setFrom(['xxxxx@163.com' => '我是管理员']);//设置发送人信息 账户,名称
$message->setSubject($subject); //邮件主题
$message->setBody($content); //设置发送内容
$message->setCharset($config['charset']); //设置字符集
$message->setContentType($config['content_type']);//设置文本类型
$message->attach(Swift_Attachment::fromPath('test.jpg', 'image/jpeg')
->setFilename('rename_test.jpg'));//发送附件
六、 发送邮件
try{
$mailer->send($message); //发送
return true;
}catch (Swift_ConnectionException $e) {
echo $e->getMessage();
return false;
}
以下为封装的邮件发送类
<?php
class Email {
/**
* @param $to_user string 接收方邮件
* @param $subject string 邮件主题
* @param $content string 邮件内容
* @return bool
*/
public static function send_email($to_user, $subject, $content)
{
//引入swiftmailer文件
require_once 'swiftmailer/lib/swift_required.php';
//获取传输对象 设置stmp服务器地址
$transport = Swift_SmtpTransport::newInstance(config('email.host'), config('email.port'), config('email.security'));
$transport->setUsername(config('email.user'));//设置用户名
$transport->setPassword(config('email.pwd'));//设置密码(密码为授权码)
//实例化发送邮件对象
$mailer = Swift_Mailer::newInstance($transport);
//实例化邮件信息对象 设置发送主题 内容 字符集 发送对象
$message = Swift_Message::newInstance();
$message->setTo($to_user); //邮件接收对象
$message->setFrom([config('email.user') => config('email.fromname')]);//设置发送人信息 账户,名称
$message->setSubject($subject); //邮件主题
$message->setBody($content); //设置发送内容
$message->setCharset(config('email.charset')); //设置字符集
$message->setContentType(config('email.content_type'));//设置文本类型
//$message->attach(Swift_Attachment::fromPath('test.jpg', 'image/jpeg')->setFilename('rename_test.jpg'));//发送附件
try{
$mailer->send($message); //发送
return true;
}catch (Swift_ConnectionException $e) {
echo 'There was a problem communicating with SMTP '.$e->getMessage();
return false;
}
}
}
配置文件
<?php
return [
'host' => 'smtp.163.com', //stmp服务器
'port' => 25, //端口
'security' => null, //安全码
'user' => 'xxx@163.com', //发送方邮箱
'fromname' => 'o2o电商网', //发送用方户名
'pwd' => '336633', //密码(授权码)
'content_type' => 'text/html', //邮件文本类型
'charset' => 'utf-8', //邮件字符集
];