PHPMailer远程SMTP配置与注意事项
本示例详细解析利用PHPMailer类库通过远程SMTP服务器实现邮件发送的具体步骤,供开发者参考与实践。
PHPMailer是功能强大的PHP邮件发送组件,既支持本地SMTP也支持远程SMTP服务。然而,配置不当易导致发送失败或无法调用。本文将结合实战经验,梳理该类库的核心用法及关键注意事项。
首先需获取PHPMailer类库文件,可通过指定链接下载,仅需少量资源分。下载地址:https://www.jb51.net/codes/27188.html
下载完成后,将核心文件class.phpmailer.php放置于项目指定目录中。在需要执行邮件发送逻辑的代码位置,按如下方式初始化调用:
<?php
require 'class.phpmailer.php';
try {
$mail = new PHPMailer(true);
$body = file_get_contents('contents.html'); //邮件的内容写到contents.html页面里了
$body = preg_replace('//////','', $body); //Strip backslashes
$mail->IsSMTP(); // tell the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP server port
$mail->Host = "mail.yourdomain.com"; // 远程SMTP服务器
$mail->Username = "yourname@yourdomain.com"; // 远程SMTP 服务器上的用户名
$mail->Password = "yourpassword"; // 你的远程SMTP 服务器上用户对应的密码
//$mail->IsSendmail(); //告诉这个类使用Sendmail组件,使用的时候如果没有sendmail组建就要把这个注释掉,否则会有
$mail->AddReplyTo("yourname@yourdomain.com","First Last");
$mail->From = "fromname@yourdomain.com";
$mail->FromName = "First Last";
$to = "toname@domain.com";
$mail->AddAddress($to);
$mail->Subject = "First PHPMailer Message";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap
$mail->MsgHTML($body);
$mail->IsHTML(true); // send as HTML
$mail->Send();
echo 'Message has been sent.';
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
?>
特别提示:务必注释掉代码中的$mail->IsSendmail();语句。若保留该配置且系统未安装sendmail组件,程序运行时会抛出“Could not execute: /var/qmail/bin/sendmail”异常,导致流程中断。
上述内容旨在帮助开发者规避常见配置陷阱,顺利实现基于PHPMailer的邮件发送功能。