PHPMailer, SMTP connect() failed error with Gmail

2020-02-14 07:09发布

I’m trying to make a contact form and I’m using PHPMailer. I tried that on localhost with xampp and it works perfect. But when i upload to my host i get the error SMTP connect() failed.

Here is my code:

$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');

I've tried to change the port to 587 and the SMTPsecure to tls (and all the combinations). But doesn’t work. Any advice to solve this?

Thanks

2条回答
家丑人穷心不美
2楼-- · 2020-02-14 07:26

This answer work form me: https://stackoverflow.com/a/47205296/2171764

I use:

$mail->Host = 'tls://smtp.gmail.com:587';
$mail->SMTPOptions = array(
   'ssl' => array(
     'verify_peer' => false,
     'verify_peer_name' => false,
     'allow_self_signed' => true
    )
);
查看更多
对你真心纯属浪费
3楼-- · 2020-02-14 07:42

You may need to specify the address from which the message is going to be sent, like this:

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

I would also give isHTML a parameter, either true or false:

$m->isHTML(true);

Another option is trying to drop the port specification all together. There are several other parameters that you may find useful. The following example is code I've tested, see if you can adapt it for your uses:

$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");
}

Hope this helps!

查看更多
登录 后发表回答