下面的代码演示了 PHPMailer 的使用方法,注意 PHPMailer 实例的配置过程。
<?php
require_once 'PHPMailer/class.phpmailer.php';
require_once 'PHPMailer/class.smtp.php';
class QQMailer
{
public static $HOST = 'smtp.qq.com'; // QQ 邮箱的服务器地址
public static $PORT = 465; // smtp 服务器的远程服务器端口号
public static $SMTP = 'ssl'; // 使用 ssl 加密方式登录
public static $CHARSET = 'UTF-8'; // 设置发送的邮件的编码
private static $USERNAME = '123456789@qq.com'; // 授权登录的账号
private static $PASSWORD = '****************'; // 授权登录的密码
private static $NICKNAME = 'yuanjin'; // 发件人的昵称
public function __construct($debug = false)
{
$this->mailer = new PHPMailer();
$this->mailer->SMTPDebug = $debug ? 1 : 0;
$this->mailer->isSMTP(); // 使用 SMTP 方式发送邮件
}
public function getMailer()
{
return $this->mailer;
}
private function loadConfig()
{
$this->mailer->SMTPAuth = true; // 开启 SMTP 认证
$this->mailer->Host = self::$HOST; // SMTP 服务器地址
$this->mailer->Port = self::$PORT; // 远程服务器端口号
$this->mailer->SMTPSecure = self::$SMTP; // 登录认证方式
/* Account Settings */
$this->mailer->Username = self::$USERNAME; // SMTP 登录账号
$this->mailer->Password = self::$PASSWORD; // SMTP 登录密码
$this->mailer->From = self::$USERNAME; // 发件人邮箱地址
$this->mailer->FromName = self::$NICKNAME; // 发件人昵称(任意内容)
$this->mailer->isHTML(true); // 邮件正文是否为 HTML
$this->mailer->CharSet = self::$CHARSET; // 发送的邮件的编码
}
public function addFile($path)
{
$this->mailer->addAttachment($path);
}
public function send($email, $title, $content)
{
$this->loadConfig();
$this->mailer->addAddress($email); // 收件人邮箱
$this->mailer->Subject = $title; // 邮件主题
$this->mailer->Body = $content; // 邮件信息
return (bool)$this->mailer->send(); // 发送邮件
}
}
require_once 'QQMailer.php';
$mailer = new QQMailer(true);
$title = '愿得一人心,白首不相离。';
$content = <<< EOF
<p align="center">
皑如山上雪,皎若云间月。<br>
闻君有两意,故来相决绝。<br>
今日斗酒会,明旦沟水头。<br>
躞蹀御沟上,沟水东西流。<br>
凄凄复凄凄,嫁娶不须啼。<br>
愿得一人心,白首不相离。<br>
竹竿何袅袅,鱼尾何簁簁!<br>
男儿重意气,何用钱刀为!</p>
EOF;
$mailer->send('123456789@qq.com', $title, $content);
远近互联前端小秦整理发布,希望能对学习技术的你有所帮助
远近互联专业提供网站建设、APP开发、网站优化、外贸网站SEO、微信运营的品牌整合营销服务让客户通过网络品牌建立与网络传播提高业绩。