如何通过 PHP 向 GMail 发送电子邮件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38777444/
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
How do I send emails through PHP to GMail?
提问by John Doe
I'm guessing that this:
我猜这是:
<?php
$emailTo = '[email protected]';
$subject = 'I hope this works!';
$body = 'Blah';
$headers='From: [email protected]'
mail($emailTo, $subject, $body, $headers);
?>
is not going to cut it. I searched for ways that I can send to email with SMTP auth and mail clients and programs such as PHPMailer, but I don't have a concise and direct answer yet thats helpful. Basically, I want a way to send emails to gmail, hotmail, etc (which will be my email) from another email (sender) through a form on my website
不会削减它。我搜索了可以使用 SMTP 身份验证和邮件客户端以及 PHPMailer 等程序发送到电子邮件的方法,但我没有一个简洁直接的答案,但这很有帮助。基本上,我想要一种通过我网站上的表单从另一封电子邮件(发件人)向 gmail、hotmail 等(这将是我的电子邮件)发送电子邮件的方法
Questions:
问题:
- Do I need to download a 3rd party library to this?
- If not, how can I change the code above to make it work.
- 我需要为此下载第 3 方库吗?
- 如果没有,我该如何更改上面的代码以使其工作。
Thanks!
谢谢!
回答by msantos
Use PHPMailer library.It is better than use mail native function because in PHPMailer you can use user authentication to avoid to send the email to spam.You can use this library without to configure a mail server. You can download in this link https://github.com/PHPMailer/PHPMailer
使用PHPMailer库。它比使用邮件本机功能更好,因为在PHPMailer中您可以使用用户身份验证来避免将电子邮件发送到垃圾邮件。您可以使用该库而无需配置邮件服务器。你可以在这个链接下载https://github.com/PHPMailer/PHPMailer
See an example:
看一个例子:
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Port = 587; // SMTP port
$mail->Username = "[email protected]"; // username
$mail->Password = "yourpassword"; // password
$mail->SetFrom('[email protected]', 'Test');
$mail->Subject = "I hope this works!";
$mail->MsgHTML('Blah');
$address = "[email protected]";
$mail->AddAddress($address, "Test");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}