我的网站上有一个PHP驱动的HTML联系人表单。目前我使用PHP mail()函数。因此,我必须做许多用户输入验证,以避免电子邮件头注入攻击。我认为我是安全的,但我可能忘记了一些东西,我想转移到一个坚实的PHP电子邮件库。我选择的库是Swiftmailer。
现在我想检查Swiftmailer地址是否如下:
- 删除或转义发件人名称中的
<
和>
字符。 - 从发件人名称中删除换行符(
'n
,'r'n
…) - 从邮件主题中删除或转义换行符。
- 规范邮件正文(邮件内容)中的换行符。根据PHP文档,
'n
应该用于内容,'r'n
应该用作邮件标题分隔符。
PS:我试图联系Swiftmailer团队与我的问题没有成功,所以我在这里尝试。
编辑:我用Swiftmailer做了一些测试用例,这是我到目前为止发现的:
- 当您的发件人名称中有
<
或>
时,您将收到无法交付电子邮件错误邮件。这可能在某种程度上导致对邮件服务器的DOS攻击(也许我错了)。这正常吗?! - 换行符被转义,因此注入攻击失败。
- 换行符被转义,因此注入攻击失败。
- 测试,但我无法看到Swiftmailer做什么(如果它做什么)。所以我还是在黑暗中。
编辑:这个答案可能已经过时了。在我写这篇文章的时候,SwiftMailer库出现了一些问题。在这一点上,SwiftMailer
的一切都很好,并且被认为是比PHPMailer
更好的库,提供了更多的功能。
我建议你使用phpmailer。它是我用过的最稳定的邮件库之一。下面是一个应该可以工作的示例代码:
include("./phpmailer/class.phpmailer.php");
$mail = new PHPMailer(false); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP();
$mail->Host = "YourDomainName.com";
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "YourSMTPMailServer.com";
$mail->Port = 587;
$mail->Username = "your-auth-user@yoursmtpmailsercer.com";
$mail->Password = "password"; // GMAIL password
$mail->AddAddress("sendToThis@email.com", '<< >> ! " Receiver Name');
$mail->SetFrom('sendFROMthis@email.com', '<< >> ! " Sender Name');
$mail->Subject = "A testing subject";
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
$mail->MsgHTML('This is my <b>html</b> testing email, sent '.time());
$mail->Send();
你需要配置它,使它连接到你的电子邮件服务器,但它应该是工作的。Phpmailer逃脱了目前我所尝试的一切。我唯一检查的是"sendToThis@email.com"。我使用下面的代码:
$email = "sendToThis@email.com";
$email = filter_var(filter_var($email,FILTER_SANITIZE_EMAIL),FILTER_VALIDATE_EMAIL);
if($email){
echo "This email is valid!";
} else {
echo "This email is INVALID!";
}
我希望这对你有帮助。