@t
oc
安装
composer require phpmailer/phpmailer
发送邮件
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@example.com';
$mail->Password = 'secret';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');
$mail->addAddress('ellen@example.com');
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
$mail->addAttachment('/var/tmp/file.tar.gz');
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
标题正文乱码
原因
因为默认采用的编码是iso-8859-1
public $CharSet = self::CHARSET_ISO88591;
如果我们的文件编码是UTF-8,按默认配置发送收到的可能是乱码。(很神奇,QQ邮箱可以自己识别)。
解决办法
$mail = new PHPMailer(true);
...
$mail->CharSet = PHPMailer::CHARSET_UTF8;
...
$ret = $mail->send();
指定ip 发送
场景
有时候我们的服务器会绑多个ip,但要指定特定ip发送。
代码
$mail = new PHPMailer(true);
...
$mail->SMTPOptions = array(
'socket' => array(
'bindto' => "127.0.0.2:0",
),
);
...
$ret = $mail->send();
效果
打开收到的邮件,查看原文。可以找到发送邮件的地址。如果是新设定的ip,说明配置成功。
Received: from xxxx (127.0.0.2 [127.0.0.2])…