首页 > 解决方案 > 为什么标头阻止邮件发送?

问题描述

这可能听起来像以前提出的问题,但相信我不是

我试图通过LocalhostHostinger 服务器mail()的 PHP函数发送使用 HTML 模板的电子邮件,但它们产生了不同的问题。

  1. 在本地主机上,尽管有标题,但电子邮件仍以纯文本形式发送

     $headers =
         "MIME-Version: 1.0\r\n" . 
         "Content-Type: text/html; charset=UTF-8";
    

    我已经在stackoverflow中解决了所有类似的问题,并尝试了每一件事,但我无法让它发挥作用。在对此进行了更多研究后,我发现了这一点

    我假设,您的电子邮件客户端正在考虑 smtp 服务器“不安全”,因此只会将所有 html 显示为纯文本,而不是呈现它

  2. 因此,我切换了主机并尝试做同样的事情,但这次我发现headers是导致问题的原因。header如果在函数中传递变量,则不会发送电子邮件mail()。我试图连接不起作用的标题。然后我制作了一组标题并将它们与 php 一起加入,implode这也不起作用。html, head, body在 stackoverflow 上的一个类似问题上,我发现如果使用标签时,webmails 会搞砸xhtml。我删除了它们,但仍然没有成功。

我也试过error reporting了,它显示module sqlite3 already loaded我认为与邮件无关。

下面是我的代码

php

<?php
 $email_template = file_get_contents("path/to/my/template");
 $lucky_number = rand(999999, 111111);
 $email_template = str_replace("{{user}}", "User", $email_template);
 $email_template = str_replace("{{lucky_number}}", $lucky_number, $email_template);
 $sender = "from:iusername@host.com"; // I found that if I dont use from, my mail ends up in spam folder
 $receiver = "username@host.com";
 $subject = "Random Subject Name";
 $headers =
    "MIME-Version: 1.0\r\n" . 
    "Content-Type: text/html; charset=UTF-8";

 if(mail($receiver, $subject, $email_template, $sender, $headers))
 {
    echo "Email Sent Successfully";
 }
 else
 {
    echo "Email Sending Failed";
 }

PS 我不能使用 PHPMailer 或其他类似的库

标签: phpemailhtml-email

解决方案


发件人信息应在标头内

因此,请更改以下行:

 $headers =
    "MIME-Version: 1.0\r\n" . 
    "Content-Type: text/html; charset=UTF-8";

 if(mail($receiver, $subject, $email_template, $sender, $headers))
 

$sender = "iusername@host.com";

$headers = "From: $sender <$sender>\r\nReply-To: $sender\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";

 if(mail($receiver, $subject, $email_template, $headers))

推荐阅读