phpmail gmail无法连接到SMTP

时间:2017-12-10 16:49:20

标签: smtp gmail phpmailer

尝试使用下面的代码,该代码已经使用多年,直到上周。也许在Gmail方面有些变化。但即使尝试了各种组合,它也无法正常工作。   允许不安全的应用程序仍然无法连接SMTP

<?php
sendMail("tosomeid@gmail.com", "fromsomeid@gmail.com", "test", "test msg<br>hello!");

function sendMail($to, $from, $subject, $message) {   
    try {
        //$to='tosomeid@gmail.com';
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
        $headers .= 'From:' . $from . ' <fromsomeid@gmail.com>' . "\r\n";
        ini_set("sendmail_from", "fromsomeid@gmail.com");
        require_once("class.phpmailer.php");
        require_once("class.smtp.php");
        set_time_limit(240);
        $mail = new PHPMailer(true);
        $mail->IsSMTP();  // telling the class to use SMTP 
        $mail->SMTPAutoTLS = false;
        $mail->Host = "smtp.gmail.com";
        $mail->SMTPDebug = 4;
        $mail->SMTPAuth = true;                  // enable SMTP authentication
        $mail->Port = 587; // or 587                    // set the SMTP port for the GMAIL server
        $mail->Username = "fromsomeid@gmail.com"; // SMTP account username
        $mail->Password = "password123"; // SMTP account password
        $mail->From = "fromsomeid@gmail.com";
        $mail->SMTPSecure = 'tls';

        $mail->AddAddress("tosomeid@gmail.com");
        $mail->SetFrom('fromsomeid@gmail.com', $from);
        $mail->AddReplyTo("fromsomeid@gmail.com", $from);
        $mail->AddBCC("tosomeid@gmail.com");
        $mail->IsHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $message;
        $mail->WordWrap = 50;
        echo 'sendMail to=>' . $to;
        if (!$mail->Send()) {
            echo 'Message was not sent.';
            echo 'Mailer error: ' . $mail->ErrorInfo;
        } else {
            echo '<br>Message was sent successfully to selected recipients.';
        }
    } catch (Exception $ex) {

        echo'EXCEPTION <br>';
        echo '<br>Caught exception: ' . $ex->getMessage() . "\n".$ex->getTraceAsString();
    }
}

?> 

1 个答案:

答案 0 :(得分:0)

您将SMTPOption添加到配置Phpmailer

$mail->SMTPOptions = array(
'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
)

);