PHPMailer发送smtp邮件

PHPMailer发送smtp邮件

最近帮朋友开发微信公众帐号的时候需要发送邮件提醒。为了节省成本,微信的接口服务器使用了PHP。 在github上找了一下选择了PHPMailer。PHPMailer的使用可以参照项目的README:

require \'PHPMailerAutoload.php\';  
$mail = new PHPMailer;  
//$mail->SMTPDebug = 3;                               // Enable verbose debug output  
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = \'smtp1.example.com;smtp2.example.com\';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = \'user@example.com\';                 // SMTP username
$mail->Password = \'secret\';                           // SMTP password
$mail->SMTPSecure = \'tls\';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to
$mail->setFrom(\'from@example.com\', \'Mailer\');
$mail->addAddress(\'joe@example.net\', \'Joe User\');     // Add a recipient
$mail->addAddress(\'ellen@example.com\');               // Name is optional
$mail->addReplyTo(\'info@example.com\', \'Information\');
$mail->addCC(\'cc@example.com\');
$mail->addBCC(\'bcc@example.com\');
$mail->addAttachment(\'/var/tmp/file.tar.gz\');         // Add attachments
$mail->addAttachment(\'/tmp/image.jpg\', \'new.jpg\');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML
$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\';
if(!$mail->send()) {
    echo \'Message could not be sent.\';
    echo \'Mailer Error: \' . $mail->ErrorInfo;
} else {
    echo \'Message has been sent\';
}

其中需要替换发件邮箱、smtp服务器地址、端口、认证方式等信息。

require_once(\"mail/PHPMailerAutoload.php\"); 
    ……
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = \"smtp.exmail.qq.com\";
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->SMTPSecure = \"ssl\";        
$mail->Username = \"admin@trumanliu.com\";
$mail->Password = \"你猜\";
$mail->AddReplyTo(\"admin@trumanliu.com\", \'yangyangliu\');
$mail->AddAddress($tomail);
$mail->SetFrom(\"admin@trumanliu.com\", \'yangyangliu\');
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->MsgHTML($body);
if(!$mail->Send()){
    echo \"邮件发送失败. <p>\";
    echo \"错误原因: \" . $mail->ErrorInfo;
}else{
    echo \"success\";
}  

如果这样的话有部分邮箱会出现中文乱码的现象,比如最近被爆的体无完肤的网易邮箱。为了修正中文乱码需要添加:

$mail->CharSet = \"utf-8\";   

发表评论

电子邮件地址不会被公开。 必填项已用*标注