PHPMailer,SMTP connect()失败,出现Gmail错误


PHPMailer, SMTP connect() failed error with Gmail

我正在尝试制作一个联系人表单,我正在使用PHPMailer。我用xampp在localhost上尝试过,效果非常好。但是当我上传到我的主机时,我得到了错误SMTP连接()失败。

这是我的代码:

$m = new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
$m->Host = "smtp.gmail.com";
$m->Username = "mymail@gmail.com";
$m->Password = "mypass";
$m->SMTPSecure = "ssl";
$m->Port = "465";
$m->isHTML();
$m->Subject = "Hello world";
$m->Body = "Some content";
$m->FromName = "Contact";
$m->addAddress('mymail@gmail.com', 'Test');

我尝试将端口更改为587,将SMTPsecure更改为tls(以及所有组合)。但不起作用。有什么建议可以解决这个问题吗?

感谢

这个答案对我来说很有用:https://stackoverflow.com/a/47205296/2171764

我使用:

$mail->Host = 'tls://smtp.gmail.com:587';
$mail->SMTPOptions = array(
   'ssl' => array(
     'verify_peer' => false,
     'verify_peer_name' => false,
     'allow_self_signed' => true
    )
);

您可能需要指定发送消息的地址,如下所示:

$mail->From = 'user@domain.com';

我也会给isHTML一个参数,无论是true还是false:

$m->isHTML(true);

另一种选择是尝试将端口规范全部删除。您可能会发现其他几个参数很有用。下面的例子是我测试过的代码,看看你是否可以根据自己的用途进行调整:

$mail = new PHPMailer;
$mail->isSMTP();/*Set mailer to use SMTP*/
$mail->Host = 'mail.domain.com';/*Specify main and backup SMTP servers*/
$mail->Port = 587;
$mail->SMTPAuth = true;/*Enable SMTP authentication*/
$mail->Username = $username;/*SMTP username*/
$mail->Password = $password;/*SMTP password*/
/*$mail->SMTPSecure = 'tls';*//*Enable encryption, 'ssl' also accepted*/
$mail->From = 'user@domain.com';
$mail->FromName = $name;
$mail->addAddress($to, 'Recipients Name');/*Add a recipient*/
$mail->addReplyTo($email, $name);
/*$mail->addCC('cc@example.com');*/
/*$mail->addBCC('bcc@example.com');*/
$mail->WordWrap = 70;/*DEFAULT = Set word wrap to 50 characters*/
$mail->addAttachment('../tmp/' . $varfile, $varfile);/*Add attachments*/
/*$mail->addAttachment('/tmp/image.jpg', 'new.jpg');*/
/*$mail->addAttachment('/tmp/image.jpg', 'new.jpg');*/
$mail->isHTML(false);/*Set email format to HTML (default = true)*/
$mail->Subject = $subject;
$mail->Body    = $message;
$mail->AltBody = $message;
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    header("Location: ../docs/confirmSubmit.html");
}

希望这能有所帮助!