做网站的时候,有些功能需要向用户发送邮件。这项工作肯定不能由人工完成。由于我使用的服务器端语言是PHP,所以在这里介绍一下PHP如何利用PHPmailer函数包来发送email。
(一)配置环境
一、有一个电子邮箱
要让服务器帮你发邮件,也需要现有一个邮箱才行。
二、设置邮箱开启POP3/SMTP和IMAP/SMTP服务
这里以163邮箱为例
1.点击设置,点击POP3/SMTP/IMAP
邮箱设置.png
2.将POP3/SMTP和IMAP/SMTP服务 前的复选框选中
开启服务.png
3.根据要求用手机验证,设置授权码
注意:授权码很重要,要认真设置,后面有用
三、在服务器上下载PHPmailer包
在终端输入指令
sudo apt-get install libphp-phpmailer
至此,邮箱和服务器的环境配置已完成。
(二)编写php文件发送邮件
以下给出例子
//引用PHPmailer函数包的文件
require '/usr/share/php/libphp-phpmailer/class.phpmailer.php';
require '/usr/share/php/libphp-phpmailer/class.smtp.php';
$mail = new PHPMailer;
//发送者
$mail->setFrom('xxxxxxx@xxx.com');
//接收者
$mail->addAddress('xxxxxxxxx@xxx.com');
//邮件主题
$mail->Subject = 'Message sent by PHPMailer';
//邮件内容
$mail->Body = 'Hello! use PHPMailer to send email using PHP';
$mail->IsSMTP();
$mail->SMTPSecure = 'ssl';
//你的邮箱的SMTP服务器地址,以163邮箱为例
$mail->Host = 'smtp.163.com';
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->CharSet='UTF-8';
//你的邮箱地址,即(一)中你申请的邮箱
$mail->Username = "xxxxx@xxx.com";
//注意!此处的密码并非登录密码,而是(一)中提到的授权码!
$mail->Password = 'xxxxxxxxx';
//下面这条语句最好加上,以防ssl未认证通过
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if(!$mail->send())
{
echo 'Email is not sent.';
echo 'Email error: ' . $mail->ErrorInfo;
}
else
{
echo 'Email has been sent.';
}
?>
其中几个注意点在代码中我具用注释标注了,在此再强调两个最关键的点:
1.$mail->Password 的值是开启POP3/SMTP和IMAP/SMTP服务的授权码,而非邮箱##的登录密码。
2.注意添加$mail->SMTPOptions赋值语句,防止SSL认证失败,出现SMTP ERROR: ##Failed to connect to server: (0)错误。