使用phpmailer向gmail帐户发送电子邮件

时间:2015-10-18 07:52:32

标签: php

<?php
    require_once 'PHPMailer-master/class.phpmailer.php';
    require_once 'PHPMailer-master/class.phpmaileroauthgoogle.php';
    require_once 'PHPMailer-master/PHPMailerAutoload.php';
    require_once 'PHPMailer-master/class.smtp.php';
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->SMTPAuth = TRUE;

    //$mail->SMTPDebug =2;
    $mail->Host = 'smtp.gmail.com';
    $mail->Username = 'zhaider113@gmail.com';
    $mail->Password = 'password';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 587;

    $from = 'shahghafoor439@gmail.com';
    $mail->setFrom($from, 'Ghafoor Shah');
    $mail->addReplyTo($from, 'Ghafoor Shah');
    $mail->addAddress('zhaider113@gmail.com', 'zeeshan');

    $mail->Subject = 'This is subject';
    $mail->Body = 'This is the body of email';
    $mail->AltBody = 'This is the body of email';
    $mail->send();

    if (!$mail->send()) {
        echo 'Messag could not send';
        echo 'Mailer error:' . $mail->ErrorInfo;
    } else {
        echo 'mail hasbeen send';
    }
    ?>
  

我尝试发送电子邮件,但它不发送并提供错误消息,即:SMTP connect()失败。 https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting * /

2 个答案:

答案 0 :(得分:0)

尝试使用$mail->SMTPSecure = 'tls';

请参阅下面的PHPMailer&#gmail示例中的完整示例:https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps

答案 1 :(得分:0)

确保包含正确的PHPMailer库。

并进行此更改

  

某些服务器无法响应SSL(安全)。所以改变这个$mail->SMTPSecure = 'tls';

     

在您的代码中,有两个邮件发送选项 $mail->send();

//$mail->send();//Comment this
if (!$mail->send()) {
    echo 'Messag could not send';
    echo 'Mailer error:' . $mail->ErrorInfo;
} else {
    echo 'mail hasbeen send';
}

现在发送邮件 打印错误日志