<?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 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. please help.
我试过创建一个简单的邮件表单。表单本身在我的索引上。html页面,但提交到单独的“谢谢您的提交”页面,谢谢。php中,上面的php代码是嵌入的。代码提交得很完美,但从来不会发送电子邮件。请帮助。
24 个解决方案
#1
384
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.
尽管这个答案中有一些只适用于themail()函数本身的使用,但是这些故障排除步骤中的许多可以应用于任何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 this Stack Overflow answer for more details on this.
有关这方面的更多细节,请参见此堆栈溢出答案。
Make sure the mail()
function is called
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
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
bool邮件(string $to, string $subject, string $message [, string $additional_headers [, string $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.
您的web服务器应该记录所有通过它发送电子邮件的尝试。这些日志的位置会有所不同(您可能需要询问服务器管理员它们的位置),但是它们通常可以在日志下的用户根目录中找到。里面会有服务器报告的错误消息(如果有的话),与您发送电子邮件的尝试有关。
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 not one 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
The mail()
function:
邮件()函数:
Returns
TRUE
if the mail was successfully accepted for delivery,FALSE
otherwise. 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
FALSE
return 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
TRUE
return 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. - 如果你收到一个真正的返回值,并不意味着你的电子邮件一定会被发送。它只是意味着通过PHP成功地将邮件发送到服务器上的相应处理程序。在PHP的控制之外还有更多的失败点,可能导致电子邮件无法发送。
So FALSE
will help point you in the right direction whereas TRUE
does not necessarily mean your email was sent successfully. This is important to note!
所以FALSE可以帮助你找到正确的方向,而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 Mare include:
为了避免通过PHP发送的邮件被发送到收件人的垃圾邮件文件夹,您可以在PHP代码中或者其他地方做各种事情,以减少您的邮件被标记为垃圾邮件的可能性。来自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. The SPF website includes a wizard to generate the DNS information for your site.
- 使用电子邮件认证方法,如SPF和DKIM,来证明你的电子邮件和你的域名属于一起,并防止欺骗你的域名。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 (e.g.
"John Smith" <john@blacksmiths-international.com>
).- 在To字段中使用收件人的全名、真实姓名,而不仅仅是电子邮件地址(例如:“约翰·史密斯”< john@blacksmiths-international.com >)。
- Monitor your abuse accounts, such as abuse@yourdomain.com and postmaster@yourdomain.com. That means - make sure that these accounts exist, read what's sent to them, and act on complaints.
- 监控你的滥用账户,比如abuse@yourdomain.com和postmaster@yourdomain.com。这意味着——确保这些账户存在,阅读发送给他们的信息,对投诉采取行动。
- 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
);
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. If you have set it to GET
or didn't set it at all, make sure you using $_GET
to look for your form values.
如果您已经将表单方法设置为POST,请确保使用$_POST查找表单值。如果您已经将它设置为GET或根本没有设置,请确保使用$_GET查找窗体值。
Make sure the Web host supports sending email
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.
一些网络主机提供商不允许或不允许通过他们的服务器发送电子邮件。这样做的原因可能不同,但如果他们禁用了邮件发送,那么您需要使用另一种方法,即使用第三方为您发送邮件。
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.
给他们的技术支持的电子邮件(在访问了他们的在线支持或FAQ之后)应该澄清你的服务器上是否有电子邮件功能。
Make sure the localhost
mail server is configured
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,你可以使用免费的水星邮件。
You can also use SMTP to send your emails. See this great answer from Vikas Dwivedi to learn how to do this.
您还可以使用SMTP发送电子邮件。请参阅Vikas Dwivedi的这个伟大的回答,了解如何做到这一点。
Enable PHP's custom mail.log
In addition to your MTA's and PHP's log file, you can enable logging for the mail()
function specifically. 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.php for details. (It's best to enable these options in the php.ini
or .user.ini
or .htaccess
perhaps.)
有关详细信息,请参阅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/webserver设置。通常情况下,您会发送一个邮件探针到:它们的地址,然后获得一个发送报告和更具体的失败或分析:
- mail-tester.com (free/simple)
- mail-tester.com(免费/简单)
- glockapps.com (free/$$$)
- glockapps.com(免费/ $ $ $)
- senforensics.com (signup/$$$)
- senforensics.com(注册/ $ $ $)
- mailtrap.io (pro/$$$)
- mailtrap。io(pro / $ $ $)
- ultratools/…/emailTest (free/MX checks only)
- ultratools /…/ emailTest(免费/ MX检查)
- Various: http://www.verticalresponse.com/blog/7-email-testing-delivery-tools/
- 不同:http://www.verticalresponse.com/blog/7-email-testing-delivery-tools/
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()函数很方便,而且经常完成工作,但它也有缺点。幸运的是,还有其他方法可以提供更大的力量和灵活性,包括处理上面列出的许多问题:
- Most popular being: PHPMailer
- 最受欢迎的是:PHPMailer
- Likewise featureful: SwiftMailer
- 同样的英特网:SwiftMailer
- Or even the older PEAR::Mail.
- 或者更老的梨::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共享网络托管计划在邮件设置/可配置性方面受到了影响。)
#2
27
Add mail header in 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>';
}
#3
17
- Always try sending headers in mail function.
- 总是尝试在邮件功能中发送标题。
- If you are sending mail through localhost then do the smtp settings for sending mail.
- 如果您正在通过localhost发送邮件,那么请执行发送邮件的smtp设置。
- If you are sending mail through server then check the email sending feature is enabled on your server.
- 如果您正在通过服务器发送邮件,那么请检查您的服务器上是否启用了邮件发送功能。
#4
16
are you using SMTP configuration for sending your email? try using phpmailer instead. you can download the library from https://github.com/PHPMailer/PHPMailer. i created my email sending this way:
您是否使用SMTP配置来发送电子邮件?试着用phpmailer代替。您可以从https://github.com/PHPMailer/PHPMailer下载该库。我创建了这样的电子邮件:
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";
}
#5
12
it worked for me on 000webhost by doing the following :
它为我提供了以下的工作:
$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
这段代码可以工作,但是邮件收到有半个小时的延迟
#6
12
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. Upload your code to a server and try.
还有一件事。mail()函数在localhost中不工作。将代码上载到服务器并尝试。
#7
9
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
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
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();
}
?>
#8
8
If you only use the mail()
function, you need to complete the config 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. Without that, mail cannot be sent. Also, you can use PHPMail class to send.
您需要打开邮件扩展,并设置SMTP smtp_port等,以及最重要的用户名和密码。没有它,邮件就不能发送。此外,还可以使用PHPMail类发送。
#9
8
Try these two thigs separately and together:
分别试试这两种方法:
- remove the
if($_POST['submit']){}
- 删除if($ _POST['提交']){ }
- remove
$from
(just my gut) - 从(我的内脏)删除$
#10
7
You can use config email by codeigniter, example using smtp (simple way) :
您可以通过codeigniter使用配置邮件,例如使用smtp(简单的方式):
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'mail.domain.com', //your smtp host
'smtp_port' => 26, //default port 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's works for me!
这对我的作品!
#11
7
For anyone who finds this going forward, I would not recommend using 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 (i.e. Sendmail) to do the work. mail
will ONLY tell you if the MTA failed to accept it (i.e. Sendmail was down when you tried to send). 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. If you're on a shared host or don't have access to the MTA logs, you're out of luck. Sadly, the default for most vanilla installs for Linux handle it this way.
PHP的邮件函数不仅不透明,它完全依赖于使用的任何MTA(例如Sendmail)来完成这项工作。邮件只会告诉你如果MTA没有接受它(例如,当你尝试发送时Sendmail已经关闭)。它不能告诉你邮件是否成功,因为它是成功的。(正如John Conde的回答细节),你现在可以摆弄MTA的日志,希望它能告诉你关于修复失败的足够信息。如果您在共享主机上,或者没有访问MTA日志,那么您就没有运气了。遗憾的是,大多数Linux默认安装都是这样处理的。
A mail library (PHPMailer, Zend Framework 2+, etc), does something very different from mail
. What they do is they open a socket directly to the receiving mail server and then send the SMTP mail commands directly over that socket. 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).
邮件库(PHPMailer、Zend Framework 2+等)的功能与邮件非常不同。它们所做的是直接将套接字打开到接收邮件服务器,然后将SMTP邮件命令直接发送到该套接字上。换句话说,类作为它自己的MTA(注意,您可以告诉库使用mail来最终发送邮件,但是我强烈建议您不要这样做)。
What this means for you is that you can then directly see the responses from the receiving server (in PHPMailer, for instance, you can turn on debugging output). No more guessing if a mail failed to send or why.
这对您来说意味着您可以直接看到来自接收服务器的响应(例如,在PHPMailer中,您可以打开调试输出)。不要再猜测邮件是否发送失败或为什么发送。
If you're using SMTP (i.e. you're calling
isSMTP()
), you can get a detailed transcript of the SMTP conversation using theSMTPDebug
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. It also means the function is doing all the tricky parts (like headers).
您还可以获得更好的接口的好处。对于邮件,您必须设置所有的头文件、附件等。对于库,您需要有一个专门的函数来实现这一点。它还意味着函数正在执行所有棘手的部分(如header)。
#12
7
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>';
}
}
?>
#13
5
$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>";
}
#14
5
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);
?>
#15
3
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>
';
}
}
#16
3
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服务器上。
#17
2
If you're having trouble sending mails with PHP, consider an alternative like PHPMailer or SwiftMailer.
如果您在用PHP发送邮件时遇到困难,可以考虑使用PHPMailer或SwiftMailer。
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 info on how to use SwiftMailer.
有关如何使用SwiftMailer的更多信息,请参阅官方文档。
#18
2
For those who do not want to use external mailers and want to mail() on a dedicated linux server.
对于那些不希望使用外部邮件者并希望在专用linux服务器上发送()的人。
The way how php mails is described in php.ini
in section [mail function]
. Parameter sendmail-path
describes how sendmail is called. Default value is sendmail -t -i
, so if you get working sendmail -t -i < message.txt
in linux console - you will be done. You could also add mail.log
to debug and be sure mail() is really called.
php邮件的描述方式。第[邮件功能]。参数sendmail-path描述了sendmail的调用方式。默认值是sendmail -t -i,因此如果您获得了工作的sendmail -t -i < message。txt在linux控制台——您将完成。您还可以添加邮件。登录到debug并确保确实调用了mail()。
Different MTA can implement sendmail
. For example, in debian default is postfix. Configure your MTA to send mail and test it from console with sendmail -v -t -i < message.txt
. File message.txt
should contain all headers of a message and a body, destination addres for envelope will be taken from To:
header. Example:
不同的MTA可以实现sendmail。例如,在debian默认中是后缀。配置您的MTA发送邮件,并使用sendmail -v -t -i < message.txt从控制台测试邮件。文件的信息。txt应该包含消息和正文的所有头部,信封的目标添加物将从:header中取出。例子:
From: myapp@example.com
To: mymail@example.com
Subject: Test mail via sendmail.
Text body.
I prefere to use ssmtp as MTA because it is simple and do not require running daemon with opened ports. ssmtp fits only for sending mail from local host, it also can send authenticated email via your account on a public mail service. Install ssmtp and edit config /etc/ssmtp/ssmtp.conf
. To be able also to recive local system mail to unix accounts(from cron jobs, for example) configure /etc/ssmtp/revaliases
file.
我喜欢使用ssmtp作为MTA,因为它很简单,不需要运行带有开放端口的守护进程。ssmtp只适用于从本地主机发送邮件,它还可以通过公共邮件服务的帐户发送经过认证的邮件。安装ssmtp并编辑配置/etc/ssmtp/ssmtp.conf。还要能够接收本地系统邮件到unix帐户(例如来自cron jobs),配置/etc/ssmtp/revaliases文件。
Here is my config for my account on Yandex mail:
以下是我在Yandex mail上的账号配置:
root=mymail@example.com
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
AuthUser=abcde@yandex.ru
AuthPass=password
#19
2
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, it is a plugin that has everything necessary to send mail, the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled
也许问题是邮件服务器的配置,以避免这种类型的问题或你不需要担心邮件服务器的问题,我建议你使用PHPMailer,它是一个拥有一切必要的插件发送邮件,你唯一需要考虑的是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;
}
#20
1
First of all,
首先,
You might have to many parameters for the mail() function... You are able to have 5 max. mail(to,subject,message,headers,parameters);
As far as the $from
variable goes, that should automatically come from your webhost if your using linux cPanel. It automatically comes from your cPanel username and ip address.
对于mail()函数,您可能需要很多参数……你可以有5个最大值。邮件(主题,消息、头部参数);至于$from变量,如果您使用linux cPanel,它将自动来自您的webhost。它自动来自你的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. the mail($to,$subject,$message,etc.)
in that order, or else there is a chance of it not working. Let me know if this helps...
还要确保在mail()函数中有正确的变量顺序。邮件($to,$subject,$message,等等)按这个顺序排列,否则它有可能不工作。如果有帮助,请告诉我……
#21
1
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. You'll have to use an alternative mail client, pear is working for us. You'll have to send to a Gmail account with low security settings.
如果你要去一所在www.AceITLab.com上运行XAMPP的大学,你应该知道我们的教授没有告诉我们的事情:AceITLab防火墙(不是Windows防火墙)阻止了XAMPP中的水星轨道。您将不得不使用另一个邮件客户端,pear正在为我们工作。您将不得不发送到一个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.
是的,我知道,这对现实世界的电子邮件来说毫无用处。然而,就我所见,学术背景和现实世界往往没有什么共同之处。
#22
1
You can use empty() and isset() functions. If you want to make it work with different files, just modify the action='yourphp.php'
to the html I'm giving you, and store the PHP script
to that yourphp.php
file. Also you need to change your index.html
into index.php
to activate PHP functionality.
您可以使用empty()和isset()函数。如果您想让它与不同的文件一起工作,只需修改action='yourphp即可。php是我给你的,把php脚本存储到你的php中。php文件。还需要更改索引。html索引。php激活php功能。
PHP
PHP
<?php
error_reporting(0);
$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 (!(empty($_POST['name']))) {
if (!(empty($_POST['email']))){
if (!(empty($_POST['message']))){
mail ($to, $subject, $body, $from);
echo '<p>Your message has been sent!</p>';
}else{
echo '<p>Fill your message please.</p>';}
}else {
echo '<p>Fill your email please.</p>';}
}else{
echo '<p>Fill your name please.</p>';}
}else{
echo '<p>Fill the form.</p>';}
?>
HTML
HTML
<html>
<form method="post" action="?">
<table>
<tr><td>Name</td><td><input type='text' name='name' id='name'/></td></tr>
<tr><td>Email</td><td><input type='text' name='email' id='email'/></td></tr>
<tr><td>Message</td><td><input type='text' name='message' id='message'/></td></tr>
<tr><td></td><td><input type='submit' name='submit' id='submit'/></td></tr>
</table>
</form>
</html>
Best Regards!
最好的问候!
#23
0
If you are running this code on a local server (i.e your computer for development purposes) it wont send the email to the recipient. What will happen is, it will create a .txt
file in a folder named mailoutput
.
如果您正在本地服务器(i)上运行此代码。e你的电脑用于开发)它不会将电子邮件发送给收件人。它将在名为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.
如果您使用的是免费的hosing服务,如:000webhost或hostinger,那么这些服务提供商会禁用mail()功能,以防止意外地使用电子邮件欺骗、垃圾邮件等。我希望您与他们联系,看看他们是否支持这个功能。
If you are sure that the service provider supports the mail() function, you can check this PHP manual for further reference, PHP mail()
如果您确定服务提供者支持mail()函数,您可以查看PHP手册以获得进一步的参考,PHP mail()
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);
?>
Hope this helped.
希望这个有帮助。
#24
0
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
#1
384
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.
尽管这个答案中有一些只适用于themail()函数本身的使用,但是这些故障排除步骤中的许多可以应用于任何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 this Stack Overflow answer for more details on this.
有关这方面的更多细节,请参见此堆栈溢出答案。
Make sure the mail()
function is called
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
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
bool邮件(string $to, string $subject, string $message [, string $additional_headers [, string $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.
您的web服务器应该记录所有通过它发送电子邮件的尝试。这些日志的位置会有所不同(您可能需要询问服务器管理员它们的位置),但是它们通常可以在日志下的用户根目录中找到。里面会有服务器报告的错误消息(如果有的话),与您发送电子邮件的尝试有关。
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 not one 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
The mail()
function:
邮件()函数:
Returns
TRUE
if the mail was successfully accepted for delivery,FALSE
otherwise. 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
FALSE
return 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
TRUE
return 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. - 如果你收到一个真正的返回值,并不意味着你的电子邮件一定会被发送。它只是意味着通过PHP成功地将邮件发送到服务器上的相应处理程序。在PHP的控制之外还有更多的失败点,可能导致电子邮件无法发送。
So FALSE
will help point you in the right direction whereas TRUE
does not necessarily mean your email was sent successfully. This is important to note!
所以FALSE可以帮助你找到正确的方向,而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 Mare include:
为了避免通过PHP发送的邮件被发送到收件人的垃圾邮件文件夹,您可以在PHP代码中或者其他地方做各种事情,以减少您的邮件被标记为垃圾邮件的可能性。来自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. The SPF website includes a wizard to generate the DNS information for your site.
- 使用电子邮件认证方法,如SPF和DKIM,来证明你的电子邮件和你的域名属于一起,并防止欺骗你的域名。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 (e.g.
"John Smith" <john@blacksmiths-international.com>
).- 在To字段中使用收件人的全名、真实姓名,而不仅仅是电子邮件地址(例如:“约翰·史密斯”< john@blacksmiths-international.com >)。
- Monitor your abuse accounts, such as abuse@yourdomain.com and postmaster@yourdomain.com. That means - make sure that these accounts exist, read what's sent to them, and act on complaints.
- 监控你的滥用账户,比如abuse@yourdomain.com和postmaster@yourdomain.com。这意味着——确保这些账户存在,阅读发送给他们的信息,对投诉采取行动。
- 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
);
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. If you have set it to GET
or didn't set it at all, make sure you using $_GET
to look for your form values.
如果您已经将表单方法设置为POST,请确保使用$_POST查找表单值。如果您已经将它设置为GET或根本没有设置,请确保使用$_GET查找窗体值。
Make sure the Web host supports sending email
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.
一些网络主机提供商不允许或不允许通过他们的服务器发送电子邮件。这样做的原因可能不同,但如果他们禁用了邮件发送,那么您需要使用另一种方法,即使用第三方为您发送邮件。
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.
给他们的技术支持的电子邮件(在访问了他们的在线支持或FAQ之后)应该澄清你的服务器上是否有电子邮件功能。
Make sure the localhost
mail server is configured
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,你可以使用免费的水星邮件。
You can also use SMTP to send your emails. See this great answer from Vikas Dwivedi to learn how to do this.
您还可以使用SMTP发送电子邮件。请参阅Vikas Dwivedi的这个伟大的回答,了解如何做到这一点。
Enable PHP's custom mail.log
In addition to your MTA's and PHP's log file, you can enable logging for the mail()
function specifically. 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.php for details. (It's best to enable these options in the php.ini
or .user.ini
or .htaccess
perhaps.)
有关详细信息,请参阅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/webserver设置。通常情况下,您会发送一个邮件探针到:它们的地址,然后获得一个发送报告和更具体的失败或分析:
- mail-tester.com (free/simple)
- mail-tester.com(免费/简单)
- glockapps.com (free/$$$)
- glockapps.com(免费/ $ $ $)
- senforensics.com (signup/$$$)
- senforensics.com(注册/ $ $ $)
- mailtrap.io (pro/$$$)
- mailtrap。io(pro / $ $ $)
- ultratools/…/emailTest (free/MX checks only)
- ultratools /…/ emailTest(免费/ MX检查)
- Various: http://www.verticalresponse.com/blog/7-email-testing-delivery-tools/
- 不同:http://www.verticalresponse.com/blog/7-email-testing-delivery-tools/
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()函数很方便,而且经常完成工作,但它也有缺点。幸运的是,还有其他方法可以提供更大的力量和灵活性,包括处理上面列出的许多问题:
- Most popular being: PHPMailer
- 最受欢迎的是:PHPMailer
- Likewise featureful: SwiftMailer
- 同样的英特网:SwiftMailer
- Or even the older PEAR::Mail.
- 或者更老的梨::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共享网络托管计划在邮件设置/可配置性方面受到了影响。)
#2
27
Add mail header in 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>';
}
#3
17
- Always try sending headers in mail function.
- 总是尝试在邮件功能中发送标题。
- If you are sending mail through localhost then do the smtp settings for sending mail.
- 如果您正在通过localhost发送邮件,那么请执行发送邮件的smtp设置。
- If you are sending mail through server then check the email sending feature is enabled on your server.
- 如果您正在通过服务器发送邮件,那么请检查您的服务器上是否启用了邮件发送功能。
#4
16
are you using SMTP configuration for sending your email? try using phpmailer instead. you can download the library from https://github.com/PHPMailer/PHPMailer. i created my email sending this way:
您是否使用SMTP配置来发送电子邮件?试着用phpmailer代替。您可以从https://github.com/PHPMailer/PHPMailer下载该库。我创建了这样的电子邮件:
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";
}
#5
12
it worked for me on 000webhost by doing the following :
它为我提供了以下的工作:
$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
这段代码可以工作,但是邮件收到有半个小时的延迟
#6
12
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. Upload your code to a server and try.
还有一件事。mail()函数在localhost中不工作。将代码上载到服务器并尝试。
#7
9
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
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
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();
}
?>
#8
8
If you only use the mail()
function, you need to complete the config 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. Without that, mail cannot be sent. Also, you can use PHPMail class to send.
您需要打开邮件扩展,并设置SMTP smtp_port等,以及最重要的用户名和密码。没有它,邮件就不能发送。此外,还可以使用PHPMail类发送。
#9
8
Try these two thigs separately and together:
分别试试这两种方法:
- remove the
if($_POST['submit']){}
- 删除if($ _POST['提交']){ }
- remove
$from
(just my gut) - 从(我的内脏)删除$
#10
7
You can use config email by codeigniter, example using smtp (simple way) :
您可以通过codeigniter使用配置邮件,例如使用smtp(简单的方式):
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'mail.domain.com', //your smtp host
'smtp_port' => 26, //default port 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's works for me!
这对我的作品!
#11
7
For anyone who finds this going forward, I would not recommend using 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 (i.e. Sendmail) to do the work. mail
will ONLY tell you if the MTA failed to accept it (i.e. Sendmail was down when you tried to send). 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. If you're on a shared host or don't have access to the MTA logs, you're out of luck. Sadly, the default for most vanilla installs for Linux handle it this way.
PHP的邮件函数不仅不透明,它完全依赖于使用的任何MTA(例如Sendmail)来完成这项工作。邮件只会告诉你如果MTA没有接受它(例如,当你尝试发送时Sendmail已经关闭)。它不能告诉你邮件是否成功,因为它是成功的。(正如John Conde的回答细节),你现在可以摆弄MTA的日志,希望它能告诉你关于修复失败的足够信息。如果您在共享主机上,或者没有访问MTA日志,那么您就没有运气了。遗憾的是,大多数Linux默认安装都是这样处理的。
A mail library (PHPMailer, Zend Framework 2+, etc), does something very different from mail
. What they do is they open a socket directly to the receiving mail server and then send the SMTP mail commands directly over that socket. 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).
邮件库(PHPMailer、Zend Framework 2+等)的功能与邮件非常不同。它们所做的是直接将套接字打开到接收邮件服务器,然后将SMTP邮件命令直接发送到该套接字上。换句话说,类作为它自己的MTA(注意,您可以告诉库使用mail来最终发送邮件,但是我强烈建议您不要这样做)。
What this means for you is that you can then directly see the responses from the receiving server (in PHPMailer, for instance, you can turn on debugging output). No more guessing if a mail failed to send or why.
这对您来说意味着您可以直接看到来自接收服务器的响应(例如,在PHPMailer中,您可以打开调试输出)。不要再猜测邮件是否发送失败或为什么发送。
If you're using SMTP (i.e. you're calling
isSMTP()
), you can get a detailed transcript of the SMTP conversation using theSMTPDebug
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. It also means the function is doing all the tricky parts (like headers).
您还可以获得更好的接口的好处。对于邮件,您必须设置所有的头文件、附件等。对于库,您需要有一个专门的函数来实现这一点。它还意味着函数正在执行所有棘手的部分(如header)。
#12
7
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>';
}
}
?>
#13
5
$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>";
}
#14
5
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);
?>
#15
3
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>
';
}
}
#16
3
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服务器上。
#17
2
If you're having trouble sending mails with PHP, consider an alternative like PHPMailer or SwiftMailer.
如果您在用PHP发送邮件时遇到困难,可以考虑使用PHPMailer或SwiftMailer。
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 info on how to use SwiftMailer.
有关如何使用SwiftMailer的更多信息,请参阅官方文档。
#18
2
For those who do not want to use external mailers and want to mail() on a dedicated linux server.
对于那些不希望使用外部邮件者并希望在专用linux服务器上发送()的人。
The way how php mails is described in php.ini
in section [mail function]
. Parameter sendmail-path
describes how sendmail is called. Default value is sendmail -t -i
, so if you get working sendmail -t -i < message.txt
in linux console - you will be done. You could also add mail.log
to debug and be sure mail() is really called.
php邮件的描述方式。第[邮件功能]。参数sendmail-path描述了sendmail的调用方式。默认值是sendmail -t -i,因此如果您获得了工作的sendmail -t -i < message。txt在linux控制台——您将完成。您还可以添加邮件。登录到debug并确保确实调用了mail()。
Different MTA can implement sendmail
. For example, in debian default is postfix. Configure your MTA to send mail and test it from console with sendmail -v -t -i < message.txt
. File message.txt
should contain all headers of a message and a body, destination addres for envelope will be taken from To:
header. Example:
不同的MTA可以实现sendmail。例如,在debian默认中是后缀。配置您的MTA发送邮件,并使用sendmail -v -t -i < message.txt从控制台测试邮件。文件的信息。txt应该包含消息和正文的所有头部,信封的目标添加物将从:header中取出。例子:
From: myapp@example.com
To: mymail@example.com
Subject: Test mail via sendmail.
Text body.
I prefere to use ssmtp as MTA because it is simple and do not require running daemon with opened ports. ssmtp fits only for sending mail from local host, it also can send authenticated email via your account on a public mail service. Install ssmtp and edit config /etc/ssmtp/ssmtp.conf
. To be able also to recive local system mail to unix accounts(from cron jobs, for example) configure /etc/ssmtp/revaliases
file.
我喜欢使用ssmtp作为MTA,因为它很简单,不需要运行带有开放端口的守护进程。ssmtp只适用于从本地主机发送邮件,它还可以通过公共邮件服务的帐户发送经过认证的邮件。安装ssmtp并编辑配置/etc/ssmtp/ssmtp.conf。还要能够接收本地系统邮件到unix帐户(例如来自cron jobs),配置/etc/ssmtp/revaliases文件。
Here is my config for my account on Yandex mail:
以下是我在Yandex mail上的账号配置:
root=mymail@example.com
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
AuthUser=abcde@yandex.ru
AuthPass=password
#19
2
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, it is a plugin that has everything necessary to send mail, the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled
也许问题是邮件服务器的配置,以避免这种类型的问题或你不需要担心邮件服务器的问题,我建议你使用PHPMailer,它是一个拥有一切必要的插件发送邮件,你唯一需要考虑的是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;
}
#20
1
First of all,
首先,
You might have to many parameters for the mail() function... You are able to have 5 max. mail(to,subject,message,headers,parameters);
As far as the $from
variable goes, that should automatically come from your webhost if your using linux cPanel. It automatically comes from your cPanel username and ip address.
对于mail()函数,您可能需要很多参数……你可以有5个最大值。邮件(主题,消息、头部参数);至于$from变量,如果您使用linux cPanel,它将自动来自您的webhost。它自动来自你的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. the mail($to,$subject,$message,etc.)
in that order, or else there is a chance of it not working. Let me know if this helps...
还要确保在mail()函数中有正确的变量顺序。邮件($to,$subject,$message,等等)按这个顺序排列,否则它有可能不工作。如果有帮助,请告诉我……
#21
1
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. You'll have to use an alternative mail client, pear is working for us. You'll have to send to a Gmail account with low security settings.
如果你要去一所在www.AceITLab.com上运行XAMPP的大学,你应该知道我们的教授没有告诉我们的事情:AceITLab防火墙(不是Windows防火墙)阻止了XAMPP中的水星轨道。您将不得不使用另一个邮件客户端,pear正在为我们工作。您将不得不发送到一个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.
是的,我知道,这对现实世界的电子邮件来说毫无用处。然而,就我所见,学术背景和现实世界往往没有什么共同之处。
#22
1
You can use empty() and isset() functions. If you want to make it work with different files, just modify the action='yourphp.php'
to the html I'm giving you, and store the PHP script
to that yourphp.php
file. Also you need to change your index.html
into index.php
to activate PHP functionality.
您可以使用empty()和isset()函数。如果您想让它与不同的文件一起工作,只需修改action='yourphp即可。php是我给你的,把php脚本存储到你的php中。php文件。还需要更改索引。html索引。php激活php功能。
PHP
PHP
<?php
error_reporting(0);
$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 (!(empty($_POST['name']))) {
if (!(empty($_POST['email']))){
if (!(empty($_POST['message']))){
mail ($to, $subject, $body, $from);
echo '<p>Your message has been sent!</p>';
}else{
echo '<p>Fill your message please.</p>';}
}else {
echo '<p>Fill your email please.</p>';}
}else{
echo '<p>Fill your name please.</p>';}
}else{
echo '<p>Fill the form.</p>';}
?>
HTML
HTML
<html>
<form method="post" action="?">
<table>
<tr><td>Name</td><td><input type='text' name='name' id='name'/></td></tr>
<tr><td>Email</td><td><input type='text' name='email' id='email'/></td></tr>
<tr><td>Message</td><td><input type='text' name='message' id='message'/></td></tr>
<tr><td></td><td><input type='submit' name='submit' id='submit'/></td></tr>
</table>
</form>
</html>
Best Regards!
最好的问候!
#23
0
If you are running this code on a local server (i.e your computer for development purposes) it wont send the email to the recipient. What will happen is, it will create a .txt
file in a folder named mailoutput
.
如果您正在本地服务器(i)上运行此代码。e你的电脑用于开发)它不会将电子邮件发送给收件人。它将在名为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.
如果您使用的是免费的hosing服务,如:000webhost或hostinger,那么这些服务提供商会禁用mail()功能,以防止意外地使用电子邮件欺骗、垃圾邮件等。我希望您与他们联系,看看他们是否支持这个功能。
If you are sure that the service provider supports the mail() function, you can check this PHP manual for further reference, PHP mail()
如果您确定服务提供者支持mail()函数,您可以查看PHP手册以获得进一步的参考,PHP mail()
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);
?>
Hope this helped.
希望这个有帮助。
#24
0
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