首页 > 解决方案 > 无法使用 Gmail 使用 PHPMailer 发送电子邮件(无法连接服务器)

问题描述

我正在尝试使用 PHPMailer 发送电子邮件。我已经看到一些有关使用此软件包通过 Gmail 服务器发送电子邮件的主题,但我无法成功。

$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP

$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587; // or 587

$mail->Username = "myEmailAddress@gmail.com";
$mail->Password = "MyGmailPassword";
$mail->setFrom('myEmailAddress@gmail.com', 'First Last');
$mail->addAddress('MyTargetEmail@example.com', 'John Doe');

$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->Body = 'Text to be sent';

if(!$mail->send()){
    echo 'message was not sent: ' . $mail->ErrorInfo;
}
else{
    echo 'Successfully sent';
}

我的回复 :

2018-11-29 14:56:37 SMTP ERROR: Failed to connect to server:  (0)
<br>
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
<br>
message was not sent: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

标签: phpcomposer-phpphpmailer

解决方案


您将电子邮件发送到错误的端口/配置。在您的代码中,您将其发送到处理 stmp 连接的端口 587,但您通过 ssl 配置发送它(需要通过端口 465 发送)。

只需要将 ssl 的位置更改为“tls”,它就会起作用。

$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587; // or 587

推荐阅读