LMLPHP后院

使用LMLPHP和PHPMailer发送邮件技术

maybe yes 发表于 2015-03-27 23:33

前几天使用 phpmailer ,通过 smtp 的方式发送了邮件。本人用的是 126 邮箱测试的,发送纪录也保存到了邮箱的已发送里面。有个朋友问我发送邮件里面含有 HTML 会失败,发送的邮件有时候会退回,这个怎么办。一般的知名度比较高的开源应用,后台的发邮件的配置都可以选择使用 PHP mail 函数发送邮件或使用 SMTP 发送邮件。比较好的方式是使用 SMTP 来发送邮件,这样程序只是一个客户端,发送邮件成功率更高,若直接使用 mail 函数发送,一般配置比较麻烦,需要本地有邮件服务器,更容易进入垃圾箱。

下面,使用 LMLPHP 框架为例,结合 phpmailer 发送邮件,删除了抄送、回复等一些配置,代码参考。

public function mailtest(){
    require '/Users/leiminglin/Documents/GIT/GITHUB/PHPMailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.126.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'leiminglin@126.com';                 // SMTP username
    $mail->Password = 'passwd';                           // SMTP password
    $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    $mail->From = 'leiminglin@126.com';
    $mail->FromName = 'May';
    $mail->addAddress('446217858@qq.com', 'maybe yes');     // Add a recipient
    $mail->addAddress('2859*****@qq.com', 'zhang******');     // Add a recipient
    $mail->isHTML(true);                                  // Set email format to HTML

    $mail->Subject = 'mail test from leiminglin';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b><font color="red">i am red font</font>';
    $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';
    }
}

上面是 index 控制器的一个方法,CLI 运行方式如下。

$php index.php /index/mailtest
2024-04-20 08:18:02 1713572282 0.026872