简体   繁体   English

PHP 邮件 function 没有完成邮件发送

[英]PHP mail function doesn't complete sending of e-mail

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com';
    $to = 'contact@yoursite.com';
    $subject = 'Customer Inquiry';
    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) {
            echo '<p>Your message has been sent!</p>';
        } else {
            echo '<p>Something went wrong, go back and try again!</p>';
        }
    }
?>

I've tried creating a simple mail form.我试过创建一个简单的邮件表单。 The form itself is on my index.html page, but it submits to a separate "thank you for your submission" page, thankyou.php , where the above PHP code is embedded.表单本身在我的index.html页面上,但它提交到一个单独的“感谢您的提交”页面, thankyou.php ,其中嵌入了上述 PHP 代码。 The code submits perfectly, but never sends an email. How can I fix this?代码完美提交,但从未发送 email。我该如何解决这个问题?

Although there are portions of this answer that apply to only to the usage of the mail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.尽管此答案的某些部分仅适用于mail()函数本身的使用,但其中许多故障排除步骤可以应用于任何 PHP 邮件系统。

There are a variety of reasons your script appears to not be sending emails.您的脚本似乎没有发送电子邮件有多种原因。 It's difficult to diagnose these things unless there is an obvious syntax error.除非有明显的语法错误,否则很难诊断这些事情。 Without one you need to run through the checklist below to find any potential pitfalls you may be encountering.如果没有,您需要通过下面的清单来查找您可能遇到的任何潜在陷阱。

Make sure error reporting is enabled and set to report all errors确保启用错误报告并设置为报告所有错误

Error reporting is essential to rooting out bugs in your code and general errors that PHP encounters.错误报告对于根除代码中的错误和 PHP 遇到的一般错误至关重要。 Error reporting needs to be enabled to receive these errors.需要启用错误报告才能接收这些错误。 Placing the following code at the top of your PHP files (or in a master configuration file) will enable error reporting.将以下代码放在 PHP 文件的顶部(或主配置文件中)将启用错误报告。

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?请参阅如何在 PHP 中获得有用的错误消息? this answer for more details on this. -这个答案有关此的更多详细信息。

Make sure the mail() function is called确保调用了mail()函数

It may seem silly but a common error is to forget to actually place the mail() function in your code.这可能看起来很愚蠢,但一个常见的错误是忘记在代码中实际放置mail()函数。 Make sure it is there and not commented out.确保它在那里并且没有被注释掉。

Make sure the mail() function is called correctly确保正确调用了mail()函数

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )布尔邮件(字符串 $to,字符串 $subject,字符串 $message [,字符串 $additional_headers [,字符串 $additional_parameters ]])

The mail function takes three required parameters and optionally a fourth and fifth one. mail 函数接受三个必需的参数,以及可选的第四个和第五个参数。 If your call to mail() does not have at least three parameters it will fail.如果您对mail()的调用没有至少三个参数,它将失败。

If your call to mail() does not have the correct parameters in the correct order it will also fail.如果您对mail()的调用没有正确顺序的正确参数,它也会失败。

Check the server's mail logs检查服务器的邮件日志

Your web server should be logging all attempts to send emails through it.您的 Web 服务器应该记录通过它发送电子邮件的所有尝试。 The location of these logs will vary (you may need to ask your server administrator where they are located) but they can commonly be found in a user's root directory under logs .这些日志的位置会有所不同(您可能需要询问服务器管理员它们的位置),但它们通常可以在用户的​​根目录下的logs中找到。 Inside will be error messages the server reported, if any, related to your attempts to send emails.内部将是服务器报告的与您尝试发送电子邮件相关的错误消息(如果有)。

Check for Port connection failure检查端口连接失败

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP.端口阻塞是大多数开发人员在集成他们的代码以使用 SMTP 传递电子邮件时面临的一个非常常见的问题。 And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above).而且,这可以在服务器邮件日志中轻松跟踪(邮件日志服务器的位置可能因服务器而异,如上所述)。 In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default.如果您在共享主机服务器上,默认情况下端口 25 和 587 将保持被阻止。 This block is been purposely done by your hosting provider.此块是由您的托管服务提供商故意完成的。 This is true even for some of the dedicated servers.即使对于某些专用服务器也是如此。 When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.当这些端口被阻塞时,请尝试使用端口 2525 连接。如果您发现该端口也被阻塞,那么唯一的解决方案是联系您的托管服务提供商以解除这些端口的阻塞。

Most of the hosting providers block these email ports to protect their network from sending any spam emails.大多数托管服务提供商都会阻止这些电子邮件端口,以保护他们的网络不发送任何垃圾邮件。

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections.使用端口 25 或 587 进行普通/TLS 连接,使用端口 465 进行 SSL 连接。 For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.对于大多数用户,建议使用端口 587 以避免某些托管服务提供商设置的速率限制。

Don't use the error suppression operator不要使用错误抑制运算符

When the error suppression operator @ is prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.错误抑制运算符@附加到 PHP 中的表达式时,该表达式可能生成的任何错误消息都将被忽略。 There are circumstances where using this operator is necessary but sending mail is not one of them.在某些情况下,需要使用此运算符,但发送邮件不是其中之一。

If your code contains @mail(...) then you may be hiding important error messages that will help you debug this.如果您的代码包含@mail(...) ,那么您可能隐藏了有助于调试的重要错误消息。 Remove the @ and see if any errors are reported.去掉@ ,看看有没有报错。

It's only advisable when you check with error_get_last() right afterwards for concrete failures.仅当您随后使用error_get_last()检查具体故障时,才建议这样做。

Check the mail() return value检查mail()返回值

The mail() function: mail()函数:

Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.如果邮件被成功接受传递,则返回TRUE ,否则返回FALSE It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.重要的是要注意,仅仅因为邮件被接受交付,并不意味着邮件实际上会到达预定目的地。

This is important to note because:这一点很重要,因为:

  • If you receive a FALSE return value you know the error lies with your server accepting your mail.如果您收到FALSE返回值,则您知道错误在于您的服务器接受了您的邮件。 This probably isn't a coding issue but a server configuration issue.这可能不是编码问题,而是服务器配置问题。 You need to speak to your system administrator to find out why this is happening.您需要与您的系统管理员联系以了解发生这种情况的原因。
  • If you receive a TRUE return value it does not mean your email will definitely be sent.如果您收到TRUE返回值,这并不意味着您的电子邮件一定会被发送。 It just means the email was sent to its respective handler on the server successfully by PHP.这只是意味着电子邮件已通过 PHP 成功发送到服务器上的相应处理程序。 There are still more points of failure outside of PHP's control that can cause the email to not be sent.还有更多的故障点超出了 PHP 的控制范围,可能导致电子邮件无法发送。

So FALSE will help point you in the right direction whereas TRUE does not necessarily mean your email was sent successfully.所以FALSE将帮助您指出正确的方向,而TRUE并不一定意味着您的电子邮件已成功发送。 This is important to note!这一点很重要!

Make sure your hosting provider allows you to send emails and does not limit mail sending确保您的托管服务提供商允许您发送电子邮件并且不限制邮件发送

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period.许多共享虚拟主机,尤其是免费虚拟主机提供商,要么不允许从其服务器发送电子邮件,要么限制在任何给定时间段内可以发送的数量。 This is due to their efforts to limit spammers from taking advantage of their cheaper services.这是因为他们努力限制垃圾邮件发送者利用他们更便宜的服务。

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations.如果您认为您的主机有电子邮件限制或阻止发送电子邮件,请查看他们的常见问题解答以查看他们是否列出了任何此类限制。 Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.否则,您可能需要联系他们的支持人员,以验证是否对发送电子邮件有任何限制。

Check spam folders;检查垃圾邮件文件夹; prevent emails from being flagged as spam防止电子邮件被标记为垃圾邮件

Oftentimes, for various reasons, emails sent through PHP (and other server-side programming languages) end up in a recipient's spam folder.通常,由于各种原因,通过 PHP(和其他服务器端编程语言)发送的电子邮件最终会进入收件人的垃圾邮件文件夹。 Always check there before troubleshooting your code.在对代码进行故障排除之前,请务必检查那里。

To avoid mail sent through PHP from being sent to a recipient's spam folder, there are various things you can do, both in your PHP code and otherwise, to minimize the chances your emails are marked as spam.为了避免通过 PHP 发送的邮件被发送到收件人的垃圾邮件文件夹,您可以在 PHP 代码中或其他方式中执行各种操作,以最大限度地减少您的电子邮件被标记为垃圾邮件的机会。 Good tips from Michiel de Mare include: Michiel de Mare的好建议包括:

  • Use email authentication methods, such as SPF , and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name.使用电子邮件认证方法,例如SPFDKIM来证明您的电子邮件和您的域名属于同一个,并防止您的域名被欺骗。 The SPF website includes a wizard to generate the DNS information for your site. SPF 网站包含一个为您的站点生成 DNS 信息的向导。
  • Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail.检查您的反向 DNS以确保您的邮件服务器的 IP 地址指向您用于发送邮件的域名。
  • Make sure that the IP-address that you're using is not on a blacklist确保您使用的 IP 地址不在黑名单上
  • Make sure that the reply-to address is a valid, existing address.确保回复地址是有效的现有地址。
  • Use the full, real name of the addressee in the To field, not just the email-address (eg "John Smith" <john@blacksmiths-international.com> ).在“收件人”字段中使用收件人的完整真实姓名,而不仅仅是电子邮件地址(例如"John Smith" <john@blacksmiths-international.com> )。
  • Monitor your abuse accounts, such as abuse@yourdomain.example and postmaster@yourdomain.example .监控您的滥用帐户,例如abuse@yourdomain.examplepostmaster@yourdomain.example That means - make sure that these accounts exist, read what's sent to them, and act on complaints.这意味着 - 确保这些帐户存在,阅读发送给他们的内容,并对投诉采取行动。
  • Finally, make it really easy to unsubscribe.最后,让退订变得非常容易。 Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation.否则,您的用户将通过按垃圾邮件按钮取消订阅,这将影响您的声誉。

See How do you make sure email you send programmatically is not automatically marked as spam?请参阅如何确保以编程方式发送的电子邮件不会被自动标记为垃圾邮件? for more on this topic.有关此主题的更多信息。

Make sure all mail headers are supplied确保提供所有邮件标题

Some spam software will reject mail if it is missing common headers such as "From" and "Reply-to":如果邮件缺少常见的标头,例如“From”和“Reply-to”,一些垃圾邮件软件会拒绝邮件:

$headers = array("From: from@example.com",
    "Reply-To: replyto@example.com",
    "X-Mailer: PHP/" . PHP_VERSION
);
$headers = implode("\r\n", $headers);
mail($to, $subject, $message, $headers);

Make sure mail headers have no syntax errors确保邮件标头没有语法错误

Invalid headers are just as bad as having no headers.无效的标头与没有标头一样糟糕。 One incorrect character could be all it takes to derail your email.一个不正确的字符可能会导致您的电子邮件脱轨。 Double-check to make sure your syntax is correct as PHP will not catch these errors for you.仔细检查以确保您的语法正确,因为 PHP不会为您捕获这些错误。

$headers = array("From from@example.com", // missing colon
    "Reply To: replyto@example.com",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a faux From: sender不要使用虚假From: sender

While the mail must have a From: sender, you may not just use any value.虽然邮件必须有 From: 发件人,但您不能只使用任何值。 In particular user-supplied sender addresses are a surefire way to get mails blocked:特别是用户提供的发件人地址是阻止邮件的可靠方法:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses.原因:您的 Web 或发送邮件服务器未列入 SPF/DKIM 白名单以假装负责@hotmail 或@gmail 地址。 It may even silently drop mails with From: sender domains it's not configured for.它甚至可以静默地丢弃带有未配置的From:域的邮件。

Make sure the recipient value is correct确保收件人值正确

Sometimes the problem is as simple as having an incorrect value for the recipient of the email.有时问题就像电子邮件收件人的值不正确一样简单。 This can be due to using an incorrect variable.这可能是由于使用了不正确的变量。

$to = 'user@example.com';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into the mail() function call:另一种测试方法是将收件人值硬编码到mail()函数调用中:

mail('user@example.com', $subject, $message, $headers);

This can apply to all of the mail() parameters.这可以应用于所有mail()参数。

Send to multiple accounts发送到多个帐户

To help rule out email account issues, send your email to multiple email accounts at different email providers .为了帮助排除电子邮件帐户问题,请将您的电子邮件发送到不同电子邮件提供商的多个电子邮件帐户。 If your emails are not arriving at a user's Gmail account, send the same emails to a Yahoo account, a Hotmail account, and a regular POP3 account (like your ISP-provided email account).如果您的电子邮件没有到达用户的 Gmail 帐户,请将相同的电子邮件发送到 Yahoo 帐户、Hotmail 帐户和常规 POP3 帐户(如您的 ISP 提供的电子邮件帐户)。

If the emails arrive at all or some of the other email accounts, you know your code is sending emails but it is likely that the email account provider is blocking them for some reason.如果电子邮件到达所有或部分其他电子邮件帐户,则您知道您的代码正在发送电子邮件,但电子邮件帐户提供商可能出于某种原因阻止了它们。 If the email does not arrive at any email account, the problem is more likely to be related to your code.如果电子邮件未到达任何电子邮件帐户,则问题很可能与您的代码有关。

Make sure the code matches the form method确保代码与表单方法匹配

If you have set your form method to POST , make sure you are using $_POST to look for your form values.如果您已将表单方法设置为POST ,请确保您使用$_POST来查找表单值。 If you have set it to GET or didn't set it at all, make sure you use $_GET to look for your form values.如果您已将其设置为GET或根本没有设置,请确保您使用$_GET来查找您的表单值。

Make sure your form action value points to the correct location确保您的表单action值指向正确的位置

Make sure your form action attribute contains a value that points to your PHP mailing code.确保您的表单action属性包含一个指向您的 PHP 邮件代码的值。

<form action="send_email.php" method="POST">

Make sure the Web host supports sending email确保 Web 主机支持发送电子邮件

Some Web hosting providers do not allow or enable the sending of emails through their servers.一些 Web 托管服务提供商不允许或启用通过其服务器发送电子邮件。 The reasons for this may vary but if they have disabled the sending of mail you will need to use an alternative method that uses a third party to send those emails for you.原因可能会有所不同,但如果他们禁用了邮件发送,您将需要使用另一种方法,即使用第三方为您发送这些电子邮件。

An email to their technical support (after a trip to their online support or FAQ) should clarify if email capabilities are available on your server.发给他们技术支持的电子邮件(在访问他们的在线支持或常见问题解答之后)应该说明您的服务器上是否有电子邮件功能。

Make sure the localhost mail server is configured确保localhost邮件服务器已配置

If you are developing on your local workstation using WAMP, MAMP, or XAMPP, an email server is probably not installed on your workstation.如果您在本地工作站上使用 WAMP、MAMP 或 XAMPP 进行开发,那么您的工作站上可能没有安装电子邮件服务器。 Without one, PHP cannot send mail by default.没有一个,PHP 默认不能发送邮件。

You can overcome this by installing a basic mail server.你可以通过安装一个基本的邮件服务器来克服这个问题。 For Windows you can use the free Mercury Mail .对于 Windows,您可以使用免费的Mercury Mail

You can also use SMTP to send your emails.您还可以使用 SMTP 发送电子邮件。 See this great answer from Vikas Dwivedi to learn how to do this.请参阅Vikas Dwivedi这个很棒的答案,了解如何做到这一点。

Enable PHP's custom mail.log启用 PHP 的自定义mail.log

In addition to your MTA's and PHP's log file, you can enable logging for the mail() function specifically.除了 MTA 和 PHP 的日志文件之外,您还可以专门mail()函数启用日志记录 It doesn't record the complete SMTP interaction, but at least function call parameters and invocation script.它没有记录完整的 SMTP 交互,但至少记录了函数调用参数和调用脚本。

ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);

See http://php.net/manual/en/mail.configuration.php for details.有关详细信息,请参阅http://php.net/manual/en/mail.configuration.php (It's best to enable these options in the php.ini or .user.ini or .htaccess perhaps.) (最好在php.ini.user.ini.htaccess中启用这些选项。)

Check with a mail testing service检查邮件测试服务

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup.您可以使用各种交付和垃圾邮件检查服务来测试您的 MTA/网络服务器设置。 Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:通常,您将邮件探测发送到:他们的地址,然后获取交付报告和更具体的失败或分析:

Use a different mailer使用不同的邮件程序

PHP's built-in mail() function is handy and often gets the job done but it has its shortcomings . PHP 的内置mail()函数很方便,经常可以完成工作,但它也有缺点 Fortunately, there are alternatives that offer more power and flexibility including handling a lot of the issues outlined above:幸运的是,有一些替代方案可以提供更多的功能和灵活性,包括处理上述许多问题:

All of which can be combined with a professional SMTP server/service provider.所有这些都可以与专业的 SMTP 服务器/服务提供商结合使用。 (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.) (因为在电子邮件设置/配置方面,典型的 08/15 共享虚拟主机计划会受到影响。)

Add a mail header in the mail function:在邮件函数中添加邮件头:

$header = "From: noreply@example.com\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$header.= "X-Priority: 1\r\n";

$status = mail($to, $subject, $message, $header);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
  1. Always try sending headers in the mail function.始终尝试在邮件功能中发送标头。
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.如果您通过 localhost 发送邮件,请进行 SMTP 设置以发送邮件。
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.如果您通过服务器发送邮件,请检查您的服务器上是否启用了电子邮件发送功能。

If you are using an SMTP configuration for sending your email, try using PHPMailer instead.如果您使用 SMTP 配置发送电子邮件,请尝试使用PHPMailer You can download the library from https://github.com/PHPMailer/PHPMailer .您可以从https://github.com/PHPMailer/PHPMailer下载该库。

I created my email sending this way:我创建了我的电子邮件发送方式:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "p@ssw0rd"; // SMTP password

    $mail->From = "me@walalang.com";
    $mail->FromName = "System-Ad";
    $mail->AddAddress($email, $recipient_name);

    $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
    $mail->IsHTML(true);                                  // Set email format to HTML (true) or plain text (false)

    $mail->Subject = "This is a Sampleenter code here Email";
    $mail->Body    = $message;
    $mail->AltBody = "This is the body in plain text for non-HTML mail clients";
    $mail->AddEmbeddedImage('images/logo.png', 'logo', 'logo.png');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}

Just add some headers before sending mail:在发送邮件之前添加一些标题:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = 'contact@yoursite.com'; 
$subject = 'Customer Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";

$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html\r\n";
$headers .= 'From: from@example.com' . "\r\n" .
'Reply-To: reply@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing.还有一件事情。 The mail() function is not working in localhost. mail()函数在本地主机中不起作用。 Upload your code to a server and try.将您的代码上传到服务器并尝试。

It worked for me on 000webhost by doing the following:通过执行以下操作,它在 000webhost 上为我工作:

$headers  = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: ". $from. "\r\n";
$headers .= "Reply-To: ". $from. "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
$headers .= "X-Priority: 1" . "\r\n";

Enter directly the email address when sending the email:发送邮件时直接输入邮箱地址:

mail('email@gmail.com', $subject, $message, $headers)

Use '' and not "" .使用''而不是""

This code works, but the email was received with half an hour lag.此代码有效,但收到电子邮件时延迟了半小时。

Mostly the mail() function is disabled in shared hosting.大多数情况下,共享主机中禁用了mail()功能。 A better option is to use SMTP.更好的选择是使用 SMTP。 The best option would be Gmail or SendGrid.最好的选择是 Gmail 或 SendGrid。


SMTPconfig.php SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php SMTPmail.php

<?php
class SMTPClient
{

    function SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body)
    {

        $this->SmtpServer = $SmtpServer;
        $this->SmtpUser = base64_encode ($SmtpUser);
        $this->SmtpPass = base64_encode ($SmtpPass);
        $this->from = $from;
        $this->to = $to;
        $this->subject = $subject;
        $this->body = $body;

        if ($SmtpPort == "") 
        {
            $this->PortSMTP = 25;
        }
        else
        {
            $this->PortSMTP = $SmtpPort;
        }
    }

    function SendMail ()
    {
        $newLine = "\r\n";
        $headers = "MIME-Version: 1.0" . $newLine;  
        $headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;  

        if ($SMTPIN = fsockopen ($this->SmtpServer, $this->PortSMTP)) 
        {
            fputs ($SMTPIN, "EHLO ".$HTTP_HOST."\r\n"); 
            $talk["hello"] = fgets ( $SMTPIN, 1024 ); 
            fputs($SMTPIN, "auth login\r\n");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            fputs ($SMTPIN, "MAIL FROM: <".$this->from.">\r\n"); 
            $talk["From"] = fgets ( $SMTPIN, 1024 ); 
            fputs ($SMTPIN, "RCPT TO: <".$this->to.">\r\n"); 
            $talk["To"] = fgets ($SMTPIN, 1024); 
            fputs($SMTPIN, "DATA\r\n");
            $talk["data"]=fgets( $SMTPIN,1024 );
            fputs($SMTPIN, "To: <".$this->to.">\r\nFrom: <".$this->from.">\r\n".$headers."\n\nSubject:".$this->subject."\r\n\r\n\r\n".$this->body."\r\n.\r\n");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php联系电子邮件.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $to = "";
    $from = $_POST['email'];
    $subject = "Enquiry";
    $body = $_POST['name'].'</br>'.$_POST['companyName'].'</br>'.$_POST['tel'].'</br>'.'<hr />'.$_POST['message'];
    $SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);
    $SMTPChat = $SMTPMail->SendMail();
}
?>

If you only use the mail() function, you need to complete the configuration file.如果只使用mail()函数,则需要完成配置文件。

You need to open the mail expansion, and set the SMTP smtp_port and so on, and most important, your username and your password.您需要打开邮件扩展,设置SMTP smtp_port等,最重要的是您的用户名和密码。 Without that, mail cannot be sent.没有它,邮件就无法发送。 Also, you can use the PHPMail class to send.此外,您可以使用PHPMail类发送。

Try these two things separately and together:分别和一起尝试这两件事:

  1. remove the if($_POST['submit']){}删除if($_POST['submit']){}
  2. remove $from (just my gut) $from

I think this should do the trick.我认为这应该可以解决问题。 I just added an if(isset and added concatenation to the variables in the body to separate PHP from HTML.我刚刚添加了一个if(isset并将连接添加到正文中的变量以将 PHP 与 HTML 分开。

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = 'contact@yoursite.com'; 
    $subject = 'Customer Inquiry';
    $body = "From:" .$name."\r\n E-Mail:" .$email."\r\n Message:\r\n" .$message;

if (isset($_POST['submit'])) 
{
    if (mail ($to, $subject, $body, $from)) 
    { 
        echo '<p>Your message has been sent!</p>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>

For anyone who finds this going forward, I would not recommend using mail .对于任何发现这种情况的人,我不建议使用mail There's some answers that touch on this, but not the why of it.有一些答案涉及到这一点,但不是为什么

PHP's mail function is not only opaque, it fully relies on whatever MTA you use (ie Sendmail ) to do the work. PHP 的mail功能不仅不透明,它完全依赖于您使用的任何MTA (即Sendmail )来完成工作。 mail will only tell you if the MTA failed to accept it (ie Sendmail was down when you tried to send). mail只会告诉您 MTA 是否无法接受它(即,当您尝试发送时,Sendmail 已关闭)。 It cannot tell you if the mail was successful because it's handed it off.它无法告诉您邮件是否成功,因为它已将其发送出去。 As such (as John Conde's answer details), you now get to fiddle with the logs of the MTA and hope that it tells you enough about the failure to fix it.因此(如John Conde 的回答详细信息),您现在可以摆弄 MTA 的日志,并希望它能告诉您足够多的有关无法修复它的信息。 If you're on a shared host or don't have access to the MTA logs, you're out of luck.如果您在共享主机上或无权访问 MTA 日志,那么您就不走运了。 Sadly, the default for most vanilla installs for Linux handle it this way.可悲的是,大多数 Linux 香草安装的默认设置都是这样处理的。

A mail library ( PHPMailer , Zend Framework 2+, etc.), does something very different from mail .邮件库( PHPMailer 、Zend Framework 2+ 等)与mail有很大不同。 They open a socket directly to the receiving mail server and then send the SMTP mail commands directly over that socket.他们直接打开一个到接收邮件服务器的套接字,然后直接通过该套接字发送 SMTP 邮件命令。 In other words, the class acts as its own MTA (note that you can tell the libraries to use mail to ultimately send the mail, but I would strongly recommend you not do that).换句话说,该类充当它自己的 MTA(请注意,您可以告诉库使用mail最终发送邮件,但我强烈建议您不要这样做)。

This means you can then directly see the responses from the receiving server (in PHPMailer, for instance, you can turn on debugging output ).这意味着您可以直接看到来自接收服务器的响应(例如,在 PHPMailer 中,您可以打开调试输出)。 No more guessing if a mail failed to send or why.不再猜测邮件是否发送失败或原因。

If you're using SMTP (ie you're calling isSMTP() ), you can get a detailed transcript of the SMTP conversation using the SMTPDebug property.如果您正在使用 SMTP(即您正在调用isSMTP() ),您可以使用SMTPDebug属性获取 SMTP 对话的详细记录。

Set this option by including a line like this in your script:通过在脚本中包含这样的行来设置此选项:

 $mail->SMTPDebug = 2;

You also get the benefit of a better interface.您还可以从更好的界面中受益。 With mail you have to set up all your headers, attachments, etc. With a library, you have a dedicated function to do that.对于mail ,您必须设置所有标题、附件等。对于库,您有一个专门的功能来做到这一点。 It also means the function is doing all the tricky parts (like headers).这也意味着该函数正在处理所有棘手的部分(如标题)。

You can use config email by CodeIgniter .您可以使用CodeIgniter的配置电子邮件。 For example, using SMTP (simple way):例如,使用SMTP (简单方式):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => 'name@domain.com',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('name@domain.com', 'Title');
$this->email->to('emaildestination@domain.com');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!这个对我有用!

$name = $_POST['name'];
$email = $_POST['email'];
$reciver = '/* Reciver Email address */';
if (filter_var($reciver, FILTER_VALIDATE_EMAIL)) {
    $subject = $name;
    // To send HTML mail, the Content-type header must be set.
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From:' . $email. "\r\n"; // Sender's Email
    //$headers .= 'Cc:' . $email. "\r\n"; // Carbon copy to Sender
    $template = '<div style="padding:50px; color:white;">Hello ,<br/>'
        . '<br/><br/>'
        . 'Name:' .$name.'<br/>'
        . 'Email:' .$email.'<br/>'
        . '<br/>'
        . '</div>';
    $sendmessage = "<div style=\"background-color:#7E7E7E; color:white;\">" . $template . "</div>";
    // Message lines should not exceed 70 characters (PHP rule), so wrap it.
    $sendmessage = wordwrap($sendmessage, 70);
    // Send mail by PHP Mail Function.
    mail($reciver, $subject, $sendmessage, $headers);
    echo "Your Query has been received, We will contact you soon.";
} else {
    echo "<span>* invalid email *</span>";
}

Try this: 尝试这个:

<?php
    $to = "somebody@example.com, somebodyelse@example.com";
    $subject = "HTML email";

    $message = "
        <html>
        <head>
           <title>HTML email</title>
        </head>
        <body>
          <p>This email contains HTML Tags!</p>
          <table>
            <tr>
             <th>Firstname</th>
             <th>Lastname</th>
            </tr>
            <tr>
              <td>John</td>
              <td>Doe</td>
            </tr>
          </table>
        </body>
        </html>";

    // Always set content-type when sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // More headers
    $headers .= 'From: <webmaster@example.com>' . "\r\n";
    $headers .= 'Cc: myboss@example.com' . "\r\n";

    mail($to, $subject, $message, $headers);
?>

Try this尝试这个

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}

Maybe the problem is the configuration of the mail server.可能问题出在邮件服务器的配置上。 To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer .为避免此类问题或您不必担心邮件服务器问题,我建议您使用PHPMailer

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.它是一个插件,拥有发送邮件所需的一切,您唯一需要考虑的是启用 SMTP 端口(端口:25 和 465)。

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'correo@gmail.com';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('correo@gmail.com', 'my name');
    $mail->addAddress('destination@correo.com');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five, mail(to, subject, message, headers, parameters);首先,mail() 函数的参数可能太多......你最多可以有五个, mail(to, subject, message, headers, parameters);

As far as the $from variable goes, that should automatically come from your webhost if your using the Linux cPanel .$from变量而言,如果您使用 Linux cPanel ,它应该自动来自您的虚拟主机。 It automatically comes from your cPanel username and IP address.它自动来自您的 cPanel 用户名和 IP 地址。

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = 'contact@yoursite.com';
$subject = 'Customer Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";

Also make sure you have the correct order of variables in your mail() function.还要确保您的 mail() 函数中的变量顺序正确。

The mail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working. mail($to, $subject, $message, etc.)按该顺序排列,否则有可能无法正常工作。

If you're having trouble sending mails with PHP, consider an alternative like PHPMailer or SwiftMailer .如果您在使用 PHP 发送邮件时遇到问题,请考虑使用PHPMailerSwiftMailer 之类的替代方法。

I usually use SwiftMailer whenever I need to send mails with PHP.每当我需要使用 PHP 发送邮件时,我通常会使用 SwiftMailer。


Basic usage:基本用法:

require 'mail/swift_required.php';

$message = Swift_Message::newInstance()
    // The subject of your email
    ->setSubject('Jane Doe sends you a message')
    // The from address(es)
    ->setFrom(array('jane.doe@gmail.com' => 'Jane Doe'))
    // The to address(es)
    ->setTo(array('frank.stevens@gmail.com' => 'Frank Stevens'))
    // Here, you put the content of your email
    ->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');

if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
    echo json_encode([
        "status" => "OK",
        "message" => 'Your message has been sent!'
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode([
        "status" => "error",
        "message" => 'Oops! Something went wrong!'
    ], JSON_PRETTY_PRINT);
}

See the official documentation for more information on how to use SwiftMailer.有关如何使用 SwiftMailer 的更多信息,请参阅官方文档

This will only affect a small handful of users, but I'd like it documented for that small handful.这只会影响一小部分用户,但我希望为那一小部分用户记录下来。 This member of that small handful spent 6 hours troubleshooting a working PHP mail script because of this issue.由于这个问题,一小撮人中的这个成员花费了 6 个小时对一个工作的 PHP 邮件脚本进行故障排除。

If you're going to a university that runs XAMPP from www.AceITLab.com, you should know what our professor didn't tell us: The AceITLab firewall (not the Windows firewall) blocks MercuryMail in XAMPP.如果你要去一所运行来自 www.AceITLab.com 的 XAMPP 的大学,你应该知道我们的教授没有告诉我们的:AceITLab 防火墙(不是 Windows 防火墙)在 XAMPP 中阻止 MercuryMail。 You'll have to use an alternative mail client, pear is working for us.您必须使用替代邮件客户端,pear 正在为我们工作。 You'll have to send to a Gmail account with low security settings.您必须发送到安全设置较低的 Gmail 帐户。

Yes, I know, this is totally useless for real world email.是的,我知道,这对于现实世界的电子邮件完全没用。 However, from what I've seen, academic settings and the real world often have precious little in common.然而,据我所见,学术环境和现实世界往往没有什么共同之处。

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.对于那些不想使用外部邮件程序并希望在专用 Linux 服务器上发送 mail() 的人。

The way, how PHP mails, is described in php.ini in section [mail function] . PHP 发送邮件的方式在[mail function]部分的php.ini中进行了描述。

Parameter sendmail-path describes how sendmail is called.参数sendmail-path描述了 sendmail 是如何被调用的。 The default value is sendmail -t -i , so if you get a working sendmail -t -i < message.txt in the Linux console - you will be done.默认值是sendmail -t -i ,所以如果你在 Linux 控制台中得到一个工作的sendmail -t -i < message.txt - 你就完成了。 You could also add mail.log to debug and be sure mail() is really called.您还可以添加mail.log进行调试,并确保确实调用了 mail()。

Different MTAs can implement sendmail .不同的 MTA 可以实现sendmail They just make a symbolic link to their binaries on that name.他们只是在该名称上建立到他们的二进制文件的符号链接。 For example, in Debian the default is Postfix .例如,在Debian中,默认值为Postfix Configure your MTA to send mail and test it from the console with sendmail -v -t -i < message.txt .将您的 MTA 配置为发送邮件并使用sendmail -v -t -i < message.txt从控制台对其进行测试。 File message.txt should contain all headers of a message and a body, destination address for the envelope will be taken from the To: header.文件message.txt应包含消息的所有标头和正文,信封的目标地址将从To:标头中获取。 Example:例子:

From: myapp@example.com
To: mymail@example.com
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports.我更喜欢将ssmtp用作 MTA,因为它很简单,并且不需要运行带有开放端口的守护程序。 ssmtp fits only for sending mail from localhost . ssmtp 仅适用于从localhost发送邮件。 It also can send authenticated email via your account on a public mail service.它还可以通过您在公共邮件服务上的帐户发送经过身份验证的电子邮件。 Install ssmtp and edit configuration file /etc/ssmtp/ssmtp.conf .安装 ssmtp 并编辑配置文件/etc/ssmtp/ssmtp.conf To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure /etc/ssmtp/revaliases file.为了还能够接收本地系统邮件到 Unix 帐户(例如,从 cron 作业向 root 发出警报)配置/etc/ssmtp/revaliases文件。

Here is my configuration for my account on Yandex mail:这是我在 Yandex 邮件上的帐户配置:

root=mymail@example.com
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
AuthUser=abcde@yandex.ru
AuthPass=password

Make sure you have Sendmail installed in your server.确保您的服务器中安装了 Sendmail。

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.如果您检查了代码并确认那里没有问题,请转到 /var/mail 并检查该文件夹是否为空。

If it is empty, you will need to do a:如果它是空的,您将需要执行以下操作:

sudo apt-get install sendmail

if you are on an Ubuntu server.如果您在 Ubuntu 服务器上。

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial! Debian 10.0.0 ('Buster') 的Sendmail安装实际上很简单!

php.ini php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):标准sendmail包安装(允许“发送”):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:其他有用的命令:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)验证(发送能力)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes.以上耗时约5分钟。 Then I wasted 5 hours... Don't forget to check your spam folder !然后我浪费了 5 个小时……别忘了检查你的垃圾邮件文件夹

If you are running this code on a local server (ie your computer for development purposes) it won't send the email to the recipient.如果您在本地服务器(即用于开发目的的计算机)上运行此代码,它不会将电子邮件发送给收件人。 It will create a .txt file in a folder named mailoutput .它将在名为mailoutput的文件夹中创建一个.txt文件。

In the case if you are using a free hosing service, like 000webhost or hostinger , those service providers disable the mail() function to prevent unintended uses of email spoofing, spamming, etc. I prefer you to contact them to see whether they support this feature.如果您使用免费的托管服务,例如000webhosthostinger ,这些服务提供商会禁用mail()功能以防止意外使用电子邮件欺骗、垃圾邮件等。我希望您与他们联系,看看他们是否支持这一点特征。

If you are sure that the service provider supports the mail() function, you can check this PHP manual for further reference,如果您确定服务提供商支持 mail() 函数,您可以查看此 PHP 手册以供进一步参考,

PHP mail() PHP 邮件()

To check weather your hosting service support the mail() function, try running this code (remember to change the recipient email address) :要检查您的托管服务是否支持 mail() 功能,请尝试运行此代码(记得更改收件人电子邮件地址)

<?php
    $to      = 'nobody@example.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: webmaster@example.com' . "\r\n" .
        'Reply-To: webmaster@example.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>

You can use the PHPMailer and it works perfectly,here's a code example:您可以使用PHPMailer ,它可以完美运行,这是一个代码示例:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "XXXXXXXXXX@gmail.com";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("XXXXXXXXXX@gmail.com", "from-name");
        $mail->AddReplyTo("XXXXXXXXXX@gmail.com", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

You can use libmail: http://lwest.free.fr/doc/php/lib/index.php3?page=mail&lang=en 您可以使用libmail: http ://lwest.free.fr/doc/php/lib/index.php3?page=mail&lang=en

include "libmail.php";
$m = new Mail(); // Create the mail
$m->From($_POST['form']);
$m->To($_POST['to']);
$m->Subject($_POST['subject']);
$m->Body($_POST['body']);
$m->Cc($_POST['cc']);
$m->Priority(4);
// Attach a file of type 'image/gif' to be displayed in the message if possible
$m->Attach("/home/leo/toto.gif", "image/gif", "inline");
$m->Send(); // Send the mail
echo "Mail was sent:"
echo $m->Get(); // Show the mail source

You can see your errors by:您可以通过以下方式查看错误:

error_reporting(E_ALL);

And my sample code is:我的示例代码是:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = 'someone@gmail.com';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = 'someone@gmail.com';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $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;
       exit;
    }
    echo 'Message has been sent';
?>

If you're stuck with an app hosted on Hostgator, this is what solved my problem.如果您对托管在 Hostgator 上的应用程序感到困惑,就是解决我的问题的方法。 Thanks a lot to the guy who posted the detailed solution.非常感谢发布详细解决方案的人。 In case the link goes offline one day, there you have the summary:万一有一天链接掉线了,你有总结:

  • Look for the sendmail path in your server.在您的服务器中查找 sendmail 路径。 A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info: <?php phpinfo(); ?>一个简单的检查方法是在一个只有你可以访问的页面中临时编写以下代码,以读取生成的信息: <?php phpinfo(); ?> <?php phpinfo(); ?> . <?php phpinfo(); ?> . Open this page, and look for sendmail path .打开此页面,然后查找sendmail path (Then, don't forget to remove this code!) (然后,不要忘记删除此代码!)
  • Problem and fix: if your sendmail path is saying only -t -i , then edit your server's php.ini and add the following line: sendmail_path = /usr/sbin/sendmail -t -i;问题和修复:如果您的 sendmail 路径只显示-t -i ,则编辑服务器的php.ini并添加以下行: sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHP mail() function, I learned that it sends not authenticated email, what created another issue.但是,在能够使用 PHP mail()函数发送邮件后,我了解到它发送的是未经身份验证的电子邮件,这又造成了另一个问题。 The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated.邮件都掉进了我Hotmail的垃圾邮箱里,有些邮件从来没有送过,我想这与他们没有经过身份验证有关。 That's why I decided to switch from mail() to PHPMailer with SMTP, after all.毕竟,这就是为什么我决定使用 SMTP 从mail()切换到PHPMailer

It may be a problem with "From:" $email address in this part of the $headers:这部分 $headers 中的“From:”$email 地址可能有问题:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:要试用它,请发送一封不带标题部分的电子邮件,例如:

mail('user@example.com', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.如果是这种情况,请尝试使用已在您尝试发送邮件的系统上创建的电子邮件帐户。

<?php

$to       = 'name@example.com';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <name@example.com>".$eol;
$headers .= "Return-Path: Name <name@example.com>".$eol;
$headers .= "From: Name <name@example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.发送 HTML 电子邮件发送电子邮件时,您可以指定 Mime 版本、内容类型和字符集以发送 HTML 电子邮件。

Example The above example will send an HTML email message to name@example.com.示例上面的示例将向 name@example.com 发送 HTML 电子邮件消息。 You can code this program in such a way that it should receive all content from the user and then it should send an email.您可以对这个程序进行编码,使其接收用户的所有内容,然后发送电子邮件。

What solved this issue for me was that some providers don't allow external recipients when using php mail:为我解决了这个问题的是某些提供商在使用 php 邮件时不允许外部收件人:

Change the recipient ($recipient) in the code to a local recipient.将代码中的收件人($recipient)更改为本地收件人。 This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be someone@yourdomain.com.这意味着使用来自服务器域的电子邮件地址,例如,如果您的服务器域是www.yourdomain.com ,那么收件人的电子邮件应该是某人@yourdomain.com。 Upload the modified php file and retry.上传修改后的php文件并重试。 If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient).如果它仍然不起作用:将发件人 ($sender) 更改为本地电子邮件(使用与收件人相同的电子邮件)。 Upload the modified php file and retry.上传修改后的php文件并重试。

Hope this helps some!希望这会有所帮助! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

I had this problem and found that stripping back the headers helped me to get mail out.我遇到了这个问题,发现剥离标题有助于我将邮件发送出去。 So this:所以这:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:变成了这样:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.不需要 To: 标头。

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink.邮件客户端非常擅长嗅探 URL 并将它们重写为超链接。 So I didn't bother writing HTML and specifying text/html in the content-type header.所以我没有费心编写 HTML 并在 content-type 标头中指定 text/html。 I just threw new lines with \r\n in the message body.我只是在消息正文中用 \r\n 抛出了新行。 I appreciate this isn't the coding purist's approach but it works for what I need it for.我很欣赏这不是编码纯粹主义者的方法,但它可以满足我的需要。

In my case, the email was well sent but to received because the whole message was in one line of over 998 caracters.在我的例子中,email 被很好地发送但被接收,因为整个消息在一行中超过 998 个字符。 I needed to make the lines of maximum length 70 with the following line: wordwrap($email_message, 70, "\r\n");我需要使用以下行使最大长度为 70 的行: wordwrap($email_message, 70, "\r\n"); . .

https://www.rfc-editor.org/rfc/rfc5322#section-2.1.1 https://www.rfc-editor.org/rfc/rfc5322#section-2.1.1

There are two limits that this specification places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.

There are several possibilities:有几种可能性:

  1. You're facing a server problem.您正面临服务器问题。 The server does not have any mail server.该服务器没有任何邮件服务器。 So your mail is not working, because your code is fine and mail is working with type.因此,您的邮件无法正常工作,因为您的代码很好,并且邮件正在使用类型。

  2. You are not getting the posted value.您没有获得发布的价值。 Try your code with a static value.尝试使用静态值的代码。

  3. Use SMTP mails to send mail...使用 SMTP 邮件发送邮件...

对于从 gmail smtp 发送电子邮件和使用 php 邮件功能,首先你必须在本地机器上设置 sendmail,一旦设置就意味着你已经设置了本地 smtp 服务器,然后你就可以从你的帐户发送电子邮件在您的 sendmail smtp 帐户中设置,就我而言,我按照https://www.developerfiles.com/how-to-send-emails-from-localhost-mac-os-x-el-capitan/ 中的说明进行操作,并且能够设置帐户,

Provided your sendmail system works, your code must be modified as follows:如果您的 sendmail 系统正常工作,您的代码必须修改如下:

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $header ="
Content-Type: text/html; charset=UTF-8\r\n
MIME-Version: 1.0\r\n
From: \"$name\" <$email>\r\n
Reply-To: no-reply@yoursite.com\r\n
X-Mailer: yoursite.com mailer\r\n
";

    $to = '"Contact" <contact@yoursite.com>'; 
    $subject = 'Customer Inquiry';
    $body =<<<EOB
<!DOCTYPE html>
<html>
    <body>
        $message
    </body>
</html>
EOB;

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $header) !== false) { 
            echo '<p>Your message has been sent!</p>';
        } else { 
            echo '<p>Something went wrong, go back and try again!</p>'; 
        }
    }
?>

This enables you to send HTML-based emails.这使您能够发送基于 HTML 的电子邮件。

Of notable interest:值得注意的是:

  1. we built a header multilines string (each line separated by\\r\\n);我们构建了一个标题多行字符串(每行由\\r\\n 分隔);
  2. we added Content-type to express we return HTML so that you can compose better emails (you can add nay HTML code you want, including CSS, to your message as you would do in HTML page).我们添加了 Content-type 来表达我们返回 HTML 以便您可以撰写更好的电子邮件(您可以像在 HTML 页面中那样在您的消息中添加任何您想要的 HTML 代码,包括 CSS)。

Note: <<<EOB syntax requires the last EOB marker begins as the beginning pf the line and has no space or whatever character after the semicolon.注意: <<<EOB语法要求最后一个 EOB 标记作为行的开头,并且在分号之后没有空格或任何字符。

If you are using the PHP mailer then you can use the followin code. 如果您使用的是PHP邮件程序,则可以使用以下代码。 Just copy paste it, and replace the *** with your data and credentials. 只需复制粘贴,然后将***替换为您的数据和凭据即可。 And also change the value of input data name. 并更改输入数据名称的值。

<?php
    require_once ("PHPMailer/PHPMailerAutoload.php");

    $error = array();

    //var_dump($_POST);

    $message = $_POST['a'] . '<br>';
    $message.= $_POST['b'] . '<br>';
    $message.= $_POST['c'] . '<br>';
    $message.= $_POST['d'] . '<br>';
    $message.= $_POST['e'] . '<br>';
    $message.= $_POST['f'] . '<br>';
    $message.= $_POST['g'] . '<br>';
    $message.= $_POST['h'] . '<br>';
    $message.= $_POST['i'] . '<br>';
    $message.= $_POST['j'] . '<br>';
    $message.= $_POST['k'] . '<br>';

    $subject = "Visitor Query";
    $from = "******@******.com"; // example a@b.com
    $password = '******';

    $mail = new PHPMailer();
    $body = $message;
    $mail->IsSMTP();
    $mail->SMTPAuth = true; // Turn on SMTP authentication
    $mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
    $mail->SMTPDebug = 0;

    //$mail->Host = 'mail.******.com'; // Sets SMTP server
    $mail->Host = 'mail.******.com'; // Sets SMTP server
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    //$mail->Port = 25;

    $mail->Username = $from; // SMTP username
    $mail->Password = $password; // SMTP password

    $mail->AddAddress ( "******@gmail.com" );
    $mail->AddReplyTo ( "******@gmail.com", "Team");
    $mail->Subject = $subject;
    $mail->Body = $message;
    $mail->From =  $from;
    $mail->FromName = "Visitor's Query";
    $mail->ContentType = "text/html";

    if (count($error == 0)) {

         $mail->Send();

        // echo "_________________wait_______for_______ our _______ reply  !";


    } else {

        echo $error; // Show error messages
        //echo $result;
    }

    //header("location: index.php");
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM