php - 无法使用 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
解决方案
您将电子邮件发送到错误的端口/配置。在您的代码中,您将其发送到处理 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
推荐阅读
- python - 比较两个数据框列以匹配字符串或者是子字符串然后在熊猫中计数
- html - 如何使用引导程序在 Reactjs 中单行显示 4 张卡片
- cassandra - 监控 Cassandra 集群的脚本
- angular - 将结果从 api 映射到 observables
- python - 从 Python 中的网格数据集计算 30 年气候平均值
- typescript - TypeScript 忽略的接口方法参数类型
- java - 检查一个 jsonNode 是否包含一个特定的键,然后一旦它存在就提取它的值
- javascript - 一些关键事件阻止其他事件触发
- java - Java 11 命令行模块和 Maven 依赖项
- tensorflow - “稀疏交叉熵损失”中稀疏的含义?