要使用PHP安全地发送邮件可以使用PHPMailer,说明如下:
PHP 本身提供了一个mail()函数,看起来简单易用。 不幸的是,与 PHP 中的很多东西一样,它的简单性只是个幻象,事实上使用不当它可能有严重的安全问题。
Email 是一组网络协议,比 PHP 的历史还曲折。完全可以说发送邮件中的陷阱与 PHP 的mail()函数一样多,这个可能会令你有点「不寒而栗」吧。
PHPMailer 是一个流行而成熟的开源库,为安全地发送邮件提供一个易用的接口。 它关注和解决可能的陷阱,这样你可以专注于更重要的事情。
示例PHP代码如下,经 PHPMailer 5.1 测试
<?php // Include the PHPMailer library require_once('phpmailer-5.1/class.phpmailer.php'); // Passing 'true' enables exceptions. This is optional and defaults to false. $mailer = new PHPMailer(true); // Send a mail from Bilbo Baggins to Gandalf the Grey // Set up to, from, and the message body. The body doesn't have to be HTML; // check the PHPMailer documentation for details. $mailer->Sender = '[email protected]'; $mailer->AddReplyTo('[email protected]', 'Bilbo Baggins'); $mailer->SetFrom('[email protected]', 'Bilbo Baggins'); $mailer->AddAddress('[email protected]'); $mailer->Subject = 'The finest weed in the South Farthing'; $mailer->MsgHTML('<p>You really must try it, Gandalf!</p><p>-Bilbo</p>'); // Set up our connection information. $mailer->IsSMTP(); $mailer->SMTPAuth = true; $mailer->SMTPSecure = 'ssl'; $mailer->Port = 465; $mailer->Host = 'my smpt host'; $mailer->Username = 'my smtp username'; $mailer->Password = 'my smtp password'; // All done! $mailer->Send(); ?>
PHPMailer的特性
要用PHP发送邮件,PHPMailer应该是时间上最受欢迎的代码库。
PHPMailer在许多著名的开源项目想使用,如:WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla!
集成SMTP支持,不需要本地服务器即可发送。
支持使用多个TOs, CCs, BCCs and REPLY-TOs进行发送。
多种邮件形式,支持不能读取HTML的邮件客户端。
支持的编码:UTF-8 content and 8bit, base64, binary, and quoted-printable。
支持使用LOGIN, PLAIN, NTLM, CRAM-MD5 and Google’s XOAUTH2 mechanisms over SSL and TLS transports进行SMTP身份认证。
支持47中语言显示错误消息。
支持DKIM and S/MIME signing。
兼容PHP5.0及之后的版本。
还有很多其他特性,这里不意义列出了,详见:PHPMailer。