php PHP邮件功能未完成发送电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24644436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:25:33  来源:igfitidea点击:

PHP mail function doesn't complete sending of e-mail

phphtmlemail

提问by user3818620

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com';
    $to = '[email protected]';
    $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.htmlpage, but it submits to a separate "thank you for your submission" page, thankyou.php, where the above PHP code is embedded. The code submits perfectly, but never sends an email. How can I fix this?

我尝试创建一个简单的邮件表单。表单本身在我的index.html页面上,但它提交到一个单独的“感谢您提交”页面,thankyou.php上面嵌入了上述 PHP 代码。代码完美提交,但从未发送电子邮件。我怎样才能解决这个问题?

回答by John Conde

Although there are portions of this answer that apply to only to the usage of themail()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. 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 遇到的一般错误至关重要。需要启用错误报告才能接收这些错误。将以下代码放在 PHP 文件的顶部(或主配置文件中)将启用错误报告。

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

See How can I get useful error messages in PHP?this answerfor more details on this.

请参阅如何在 PHP 中获取有用的错误消息?-这个答案有关此的更多详细信息。

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. Make sure it is there and not commented out.

这可能看起来很愚蠢,但一个常见的错误是忘记mail()在代码中实际放置该函数。确保它在那里并且没有被注释掉。

Make sure the mail()function is called correctly

确保mail()函数被正确调用

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

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

The mail function takes three required parameters and optionally a fourth and fifth one. 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. 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. Inside will be error messages the server reported, if any, related to your attempts to send emails.

您的网络服务器应该记录所有通过它发送电子邮件的尝试。这些日志的位置会有所不同(您可能需要询问您的服务器管理员它们的位置),但通常可以在logs. 里面将是服务器报告的与您尝试发送电子邮件相关的错误消息(如果有)。

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. 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. 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.

端口阻塞是大多数开发人员在集成他们的代码以使用 SMTP 发送电子邮件时面临的一个非常常见的问题。而且,这可以在服务器邮件日志中轻松跟踪(邮件日志服务器的位置可能因服务器而异,如上所述)。如果您在共享托管服务器上,默认情况下端口 25 和 587 保持被阻止。此块是由您的托管服务提供商有意完成的。即使对于某些专用服务器也是如此。当这些端口被阻止时,尝试使用端口 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. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

使用端口 25 或 587 进行普通/TLS 连接,使用端口 465 进行 SSL 连接。对于大多数用户,建议使用端口 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. There are circumstances where using this operator is necessary but sending mail is notone of them.

错误抑制运算符@被添加到 PHP 中的表达式时,该表达式可能生成的任何错误消息都将被忽略。在某些情况下,使用此运算符是必要的,但发送邮件不是其中之一。

If your code contains @mail(...)then you may be hiding important error messages that will help you debug this. Remove the @and see if any errors are reported.

如果您的代码包含,@mail(...)那么您可能隐藏了重要的错误消息,这将有助于您进行调试。删除@并查看是否报告了任何错误。

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 TRUEif the mail was successfully accepted for delivery, FALSEotherwise. 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.

TRUE如果邮件被成功接受交付,FALSE则返回,否则返回。重要的是要注意,仅仅因为邮件被接受投递,并不意味着邮件实际上会到达预定目的地。

This is important to note because:

这一点很重要,因为:

  • If you receive a FALSEreturn value you know the error lies with your server accepting your mail. 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 your receive a TRUEreturn value it does not mean your email will definitely be sent. It just means the email was sent to its respective handler on the server successfully by PHP. There are still more points of failure outside of PHP's control that can cause the email to not be sent.
  • 如果您收到FALSE返回值,您就知道错误在于您的服务器接受您的邮件。这可能不是编码问题,而是服务器配置问题。您需要与系统管理员联系以找出发生这种情况的原因。
  • 如果您收到TRUE返回值,并不意味着您的电子邮件肯定会被发送。这只是意味着电子邮件已通过 PHP 成功发送到服务器上的相应处理程序。还有更多超出 PHP 控制范围的故障点会导致电子邮件无法发送。

So FALSEwill help point you in the right direction whereas TRUEdoes notnecessarily mean your email was sent successfully. This is important to note!

SoFALSE将帮助您指明正确的方向,TRUE并不一定意味着您的电子邮件已成功发送。这一点很重要!

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. Always check there before troubleshooting your code.

通常,由于各种原因,通过 PHP(和其他服务器端编程语言)发送的电子邮件最终会出现在收件人的垃圾邮件文件夹中。在对代码进行故障排除之前,请务必检查那里。

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. Good tips from Michiel de Mareinclude:

为避免通过 PHP 发送的邮件被发送到收件人的垃圾邮件文件夹,您可以在 PHP 代码和其他方面执行多种操作,以最大程度地减少电子邮件被标记为垃圾邮件的机会。Michiel de Mare 的好建议包括:

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

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: [email protected]",
    "Reply-To: [email protected]",
    "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 notcatch these errors for you.

无效的标头与没有标头一样糟糕。一个不正确的字符可能会破坏您的电子邮件。仔细检查以确保您的语法正确,因为 PHP不会为您捕获这些错误。

$headers = array("From [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a faux From:sender

不要使用假From:发件人

While the mail must have a From: sender, you may not just use anyvalue. In particular user-spplied sender addresses are a surefire way to get mails blocked:

虽然邮件必须有一个 From: 发件人,但您不能只使用任何值。特别是用户提供的发件人地址是阻止邮件的可靠方法:

$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. It may even silently drop mails with From:sender domains it's not configured for.

原因:您的 Web 或发送邮件服务器未列入 SPF/DKIM 白名单以假装对 @hotmail 或 @gmail 地址负责。它甚至可能会默默地丢弃带有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 = '[email protected]';
// 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('[email protected]', $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 $_POSTto look for your form values. If you have set it to GETor didn't set it at all, make sure you using $_GETto look for your form values.

如果您已将表单方法设置为POST,请确保您正在使用$_POST来查找表单值。如果您已将其设置为GET或根本没有设置,请确保您使用$_GET来查找表单值。

Make sure your form actionvalue points to the correct location

确保您的表单action值指向正确的位置

Make sure your form actionattribute 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. 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.

某些 Web 托管服务提供商不允许或启用通过其服务器发送电子邮件。造成这种情况的原因可能会有所不同,但如果他们禁用了邮件发送,您将需要使用替代方法,该方法使用第三方为您发送这些电子邮件。

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 localhostmail 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. Without one, PHP cannot send mail by default.

如果您使用 WAMP、MAMP 或 XAMPP 在本地工作站上进行开发,则您的工作站上可能未安装电子邮件服务器。如果没有,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. See this great answerfrom Vikas Dwivedito learn how to do this.

您还可以使用 SMTP 发送电子邮件。请参阅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()functionspecifically. It doesn't record the complete SMTP interaction, but at least function call parameters and invocation script.

除了您的 MTA 和 PHP 的日志文件之外,您还可以专门为该mail()功能启用日志记录。它不记录完整的 SMTP 交互,但至少记录函数调用参数和调用脚本。

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

See http://php.net/manual/en/mail.configuration.phpfor details. (It's best to enable these options in the php.inior .user.inior .htaccessperhaps.)

有关详细信息,请参阅http://php.net/manual/en/mail.configuration.php。(最好在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. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

您可以使用各种传送和垃圾邮件检查服务来测试您的 MTA/网络服务器设置。通常,您将邮件探测发送至:他们的地址,然后获得交付报告以及更具体的故障或分析:

Use a different mailer

使用不同的邮件程序

PHP's built in mail()function is handy and often gets the job done but it has its shortcomings. Fortunately there are alternatives that offer more power and flexibility including handling a lot of the issues outlined above:

PHP 的内置mail()函数很方便,通常可以完成工作,但它也有缺点。幸运的是,有一些替代方案可以提供更多的功能和灵活性,包括处理上面列出的许多问题:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

所有这些都可以与专业的 SMTP 服务器/服务提供商结合使用。(因为在电子邮件设置/可配置性方面,典型的 08/15 共享虚拟主机计划会受到影响。)

回答by er.irfankhan11

Add a mail header in the mail function:

在邮件函数中添加邮件头:

$header = "From: [email protected]\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>';
}

回答by sonam gupta

  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.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
  1. 始终尝试在邮件功能中发送标题。
  2. 如果您通过 localhost 发送邮件,则进行 SMTP 设置以发送邮件。
  3. 如果您通过服务器发送邮件,请检查您的服务器上是否启用了电子邮件发送功能。

回答by oneDerer

If you are using an SMTP configuration for sending your email, try using PHPMailerinstead. You can download the library from https://github.com/PHPMailer/PHPMailer.

如果您使用 SMTP 配置发送电子邮件,请尝试使用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 = "[email protected]";
    $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";
}

回答by user1258544

Just add some headers before sending mail:

只需在发送邮件之前添加一些标题:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

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

And one more thing. The mail()function is not working in localhost. Upload your code to a server and try.

还有一件事情。该mail()功能在本地主机中不起作用。将您的代码上传到服务器并尝试。

回答by bat .t

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 protected]', $subject, $message, $headers)

Use ''and not "".

使用''而不是""

This code works, but the email was received with half an hour lag.

此代码有效,但收到电子邮件时延迟了半小时。

回答by Karthik

Mostly the mail()function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.

大多数情况下,该mail()功能在共享主机中被禁用。更好的选择是使用 SMTP。最好的选择是 Gmail 或 SendGrid。



SMTPconfig.php

SMTP配置文件

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


SMTPmail.php

SMTP邮件.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

contact_email.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();
}
?>

回答by iatboy

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_portand so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use the PHPMailclass to send.

您需要打开邮件扩展,并设置SMTP smtp_port等等,最重要的是您的用户名和密码。没有它,就无法发送邮件。此外,您可以使用PHPMail该类进行发送。

回答by vldfr

Try these two things separately and together:

分别并一起尝试这两件事:

  1. remove the if($_POST['submit']){}
  2. remove $from(just my gut)
  1. 去除那个 if($_POST['submit']){}
  2. 删除$from(只是我的直觉)

回答by Stephen M

I think this should do the trick. I just added an if(issetand 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 = '[email protected]'; 
    $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>'; 
    }
}

?>