用PHP可靠地发送邮件?

时间:2019-10-01 01:09:23

标签: php smtp

当我使用PHP mail()函数时,主机(A2)有时会阻止它。当我与他们联系时,他们告知我发送邮件认为SMTP是一个更好的选择。这个准确吗?通过PHP发送邮件的最可靠方法是什么?有人可以给我一个如何使用PHP可靠地发送邮件的示例吗?

2 个答案:

答案 0 :(得分:0)

通常,通过托管SMTP服务器发送电子邮件比直接从应用程序服务器发送电子邮件更有效。只要未将SMTP服务器列入黑名单,这都是正确的。

有一些不错的PHP Mail软件包。我在项目中使用了SwiftMailer: https://swiftmailer.symfony.com/

基本方案快速示例: https://swiftmailer.symfony.com/docs/introduction.html

您可以使用PHP composer(https://getcomposer.org/

进行安装。

答案 1 :(得分:0)

根据我的经验,PHPMailer是必经之路-https://github.com/PHPMailer/PHPMailer

您需要访问将用于发送邮件的SMTP服务器。这可以是Google SMTP服务器(@ gmail.com电子邮件地址)或您公司的电子邮件服务器。

使用Google SMTP服务器执行此操作的简单示例是:

1)从终端/外壳使用composer安装PHPMailer:

composer require phpmailer/phpmailer

2)在您的php脚本中包括作曲家生成的自动加载文件和PHPMailer:

// Load Composer's autoloader
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

3)使用以下方式发送电子邮件:

$mail = new PHPMailer(true);
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
$mail->isSMTP();                                            // Send using SMTP
$mail->Host       = 'smtp.gmail.com';                    // Set the SMTP server to send through
$mail->SMTPAuth   = true;                                   // Enable SMTP authentication
$mail->Username   = 'YOUREMAIL@gmail.com';                     // SMTP username
$mail->Password   = 'YOUREMAILPASSWORD';                               // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port       = 587;                                    // TCP port to connect to

//Recipients
$mail->setFrom('YOUREMAIL@gmail.com', 'Mailer');
$mail->addAddress('TOADDRESS');     // Add a recipient

// Content
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';

$mail->send();

在以下位置阅读PHPMailer文档:https://github.com/PHPMailer/PHPMailer

相关问题