无法使用 PHPMailer 发送电子邮件

Cannot send email using PHPMailer

我正在尝试使用 phpmailer 发送电子邮件。这是我写的代码。

    $mail = new PHPMailer;

    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'shamir.towsif@gmail.com';
    $mail->Password = '*********';
    $mail->Port = 25;

    $mail->From = 'shamir.towsif@gmail.com';
    $mail->FromName = 'Shamir Towsif';
    $mail->addAddress('shamir.towsif@gmail.com', 'Shamir Towsif');
    $mail->addReplyTo('shamir.towsif@gmail.com', 'Information');

    $mail->isHTML(true);

    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if(!$mail->send()) {
        echo "Message could not be sent.\n";
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }

这是我遇到的错误。

Message could not be sent. Mailer Error: SMTP connect() failed.

我做错了什么。 SO 中的其他问题没有帮助。提前致谢。

我遇到了类似的问题,但我认为您应该尝试将此添加到您的代码中:

$mail->Port = 587;
$mail->SMTPSecure = 'tls';

这是 PHPMailer 推荐的 GMail 设置,你可以看到一个 example in their Github page .

通过将这些行添加到标准 PHPMailer 配置,解决了一个几乎相同的问题。就像一个魅力。

$mail->SMTPKeepAlive = true;   
$mail->Mailer = “smtp”; // don't change the quotes!

遵循使用 TLS 的 SMTP 的所有标准设置和端口等的默认设置。最终,我在这里研究解决方案时遇到了这段代码(来自 Simon Chen),https://webolio.wordpress.com/2008/03/02/phpmailer-and-smtp-on-1and1-shared-hosting/#comment-89

标题:使用 PhpMailer 和 Gmail 从服务器发送电子邮件

以下是我解决类似问题的方法:

  1. 从 github (https://github.com/PHPMailer/PHPMailer) 下载 PHPMAILER 到您的计算机。

  2. 将其作为 .zip 文件上传到您的服务器,然后单击提取图标将其提取。将文件夹重命名为 'phpmailer' 或您想要的任何名称。

  3. 在邮件发送.php文件中放入以下代码:

    require 'phpmailer/src/Exception.php'; require 'phpmailer/src/PHPMailer.php'; require 'phpmailer/src/SMTP.php'; $mail = new PHPMailer\PHPMailer\PHPMailer(); $mail->isSMTP(); $mail->SMTPDebug = 2; $mail->Host = 'smtp.gmail.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = "sender@gmail.com"; $mail->Password = "password"; $mail->setFrom('sender@gmail.com', 'Name'); $mail->addAddress('receiver@yahoo.com', 'Name'); $mail->Subject = 'Subject'; $mail->Body = 'This is a plain-text message body'; if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; }

  4. 保存 php 文件。

  5. 打开浏览器并登录您在 php 脚本中使用的 gmail(google) 帐户。

  6. 转到这个 link: https://support.google.com/accounts/answer/6009563

  7. 展开您的设备或应用可能不支持Google的安全标准

  8. 单击不太安全的应用程序

  9. 切换允许安全性较低的应用程序:开启(如果它是关闭).

  10. 展开应用不支持两步验证

  11. 点击link:https://accounts.google.com/DisplayUnlockCaptcha

  12. 单击继续

  13. 在浏览器中打开邮件发送php文件。

  14. 现在将发送电子邮件。

这项技术对我有用。我希望它也对你们有用。

快乐编码:-)