使用 PHP 通过 SMTP 协议发信
通过SMTP发送邮件是开发中经常会用到的功能,了解到PHP mail() 函数运行需要一个已安装且正在运行的邮件系统(如:sendmail、postfix、qmail等),感觉不是太方便,在阿里云的文档中找到了SMTP 之 PHP 调用示例,照猫画虎的操作下可成功执行,遂记录一下。
首先使用外部依赖phpmailer,需要通过github下载所需的 PHPMailer.php, Exception.php, SMTP.php,GitHub上文档是这样描述的:
Alternatively, if you're not using Composer, you can download PHPMailer as a zip file, (note that docs and examples are not included in the zip file), then copy the contents of the PHPMailer folder into one of the include_path
directories specified in your PHP configuration and load each class file manually:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
下载完后将三个文件放入开发目录中,即可使用。
使用前需修改中文编码,不然中文会乱码,打开PHPMailer.php,将77行的字符集设置:
public $CharSet = self::CHARSET_ISO88591;
修改为:
public $CharSet = self::CHARSET_UTF8;
发信示例代码:
<?php
require 'PHPMailer.php';
require 'Exception.php';
require 'SMTP.php';
$mail = new PHPMailer(true);
try {
//Server settings
$mail->Charset = 'UTF-8';
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'ssl://smtpdm.aliyun.com'; //邮件推送服务器
$mail->Port = 465; //端口
//$mail->Host = 'smtpdm.aliyun.com';
//$mail->Port = 80;
$mail->SMTPAuth = true; //授权
$mail->Username = 'test***@example.net'; //发信地址
$mail->Password = '*******'; //SMTP 密码
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //启用加密
//Recipients
$mail->setFrom('test***@example.net', 'Mailer'); //显示发信地址,可设置代发。
$mail->addAddress('test1***@example.net', 'name'); //收件人和昵称
//$mail->addAddress('test1***@example.net'); //昵称也可不填
//$mail->addAddress('test2***@example.net', 'name2');//如果需要设置多个收件人,可以再添加一条
$mail->addReplyTo('test1***@example.net', 'Information');//回信地址
$mail->addCC('test2***@example.net');//抄送人
$mail->addBCC('test3***@example.net');//密送人
//Attachments
//$mail->addAttachment('C:/Users/Documents/test.jpg'); //增加附件
$mail->addAttachment('C:/Users/Documents/test.jpg', 'new.jpg'); //名称可选
//Content
$mail->isHTML(true); //HTML 格式
$mail->Subject = 'Subject test';
$mail->Body = 'Test content';
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->Sender = 'test***@example.net';
echo 'Message has been sent';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
include 和 require 的区别
require 一般放在 PHP 文件的最前面,程序在执行前就会先导入要引用的文件;
include 一般放在程序的流程控制中,当程序执行时碰到才会引用,简化程序的执行流程。
require 引入的文件有错误时,执行会中断,并返回一个致命错误;
include 引入的文件有错误时,会继续执行,并返回一个警告。
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。