使用 SwiftMailer 发送电子邮件时 GMail 用户名和密码未被接受错误

GMail Username and Password not accepted error when sending email with SwiftMailer

当我尝试使用我的 GMail 帐户通过 SwiftMailer 从我的 PHP application 发送电子邮件时收到以下错误。

535-5.7.8 Username and Password not accepted

这是我的 SwiftMailer 代码:

$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
    ->setUsername('ayrshireminiscontact@gmail.com')
    ->setPassword('~password-in-here~');

$mailer  = Swift_Mailer::newInstance($transporter);
$message = Swift_Message::newInstance('Portfolio Enquiry')
    ->setFrom(array('ayrshireminiscontact@gmail.com' => 'CRMPicco Portfolio Enquiry'))
    ->setTo(array('picco@crmpicco.co.uk' => 'A name'))
    ->setBody($email_body);

$result = $mailer->send($message);

这是我的 Apache 错误日志和堆栈跟踪中的条目。

[Wed Aug 18 22:06:10.284728 2015] [:error] [pid 9298] [client 10.0.0.1:64806] PHP Fatal error: Uncaught exception 'Swift_TransportException' with message 'Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at\r\n535 5.7.8 https://support.google.com/mail/answer/14257 gj13sm2191931wic.22 - gsmtp\r\n"' in /var/www/portfolio/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:383\nStack trace:\n#0 /var/www/portfolio/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(281): Swift_Transport_AbstractSmtpTransport->_assertResponseCode('535-5.7.8 Usern...', Array)\n#1 /var/www/portfolio/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(243): Swift_Transport_AbstractSmtpTransport->executeCommand('RSET\r\n', Array, Array)\n#2 /var/www/portfolio/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php(54): Swift_Transport_EsmtpTransport->executeCommand('RSET\r\n', Array)\n#3 /var/www/portfolio/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php(176): Swift_Transport_Esmtp_Auth_XOAuth2Authent in /var/www/portfolio/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php on line 383, referer: https://crmpicco.dev/

我试过http://www.google.com/accounts/DisplayUnlockCaptcha,我可以通过网络浏览器登录帐户,没有任何问题。

这发生在我的本地开发机器和可公开访问的站点上。这是我的 GMail 帐户或我的实施的问题吗?

您需要 allow access from less-secure apps,因为通过密码的 IMAP 从根本上来说是不安全的。 (不可撤销)

更好的是,切换到 OAuth 身份验证。