# PHP - 使用PHPMailer发邮件

时间:2023-03-08 18:06:01

PHPMailer支持多种邮件发送方式,使用起来非常简单

1.下载PHPMailer

https://github.com/PHPMailer/PHPMailer,下载完成加压后,

# PHP - 使用PHPMailer发邮件

把下边的两个文件复制进php的根目录:

# PHP - 使用PHPMailer发邮件

2.设置邮件服务器

我们以qq邮箱为例,进入qq邮箱中,点击设置,选中账户选项,在账户下设置POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务:

# PHP - 使用PHPMailer发邮件

这里提示生成授权码,点击生成就行了,需要用手机发短信,之后得到授权码,保存下来。

3.写发邮件函数

我们这里的函数只是为了演示功能,大家可以自定义自己的函数

function sendMail($body) {
//invoke mail() function to send mail
// mail($toaddress, $subject, $mailcontent, $fromaddress);
date_default_timezone_set('Asia/Shanghai');//设定时区东八区
require_once('class.phpmailer.php');
include('class.smtp.php');
$mail = new PHPMailer; $mail->SMTPDebug = 2; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.qq.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '714034323'; // SMTP username
$mail->Password = 'budejddmfejdsedj'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; echo $mail->Host; // TCP port to connect to $mail->setFrom('714034323@qq.com', 'Mailer');
// $mail->addAddress('714080794@qq.com', 'Joe User'); // Add a recipient
$mail->addAddress('714034323@qq.com'); // Name is optional
$mail->addReplyTo('714034323@qq.com', 'Information');
// $mail->addCC('714034323@qq.com');
// $mail->addBCC('714034323@qq.com'); // $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(false); // Set email format to HTML $mail->Subject = 'Here is the subject';
$mail->Body = $body;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo ucwords('Message has been sent');
}
}

4.注意事项

$mail->Host = 'smtp.qq.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '714034323'; // SMTP username
$mail->Password = 'budejddmfejdsedj'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;

上边的设置最重要,Host不能写错,qq的邮箱是需要验证的,所有SMTPAuth设为true,Port按照qq的设置就行了。

5.发邮件

调用函数就能发邮件了,这个函数很多地方都是写死的,大家可灵活修改。有什么为题,可以留言。