我正在尝试使用Gmail SMTP从Swift Mailer发送电子邮件。它可以方便地发送电子邮件一段时间,但之后会停止发送电子邮件,特别是当我在一天左右后恢复工作时。它显示以下错误:
无法与主机smtp.gmail.com [#0]
建立连接以下是我用来发送电子邮件的示例代码:
<?php
require_once 'lib/swift_required.php';
try
{
echo '<pre>';
//Generating the Email Content
$message = Swift_Message::newInstance()
->setFrom(array('myemail@gmail.com' => 'No Reply'))
->setTo(array('recipient@gmail.com' => 'Recipient'))
->setSubject('Test Email')
->setBody("This is a Test Email to check SwiftMailer.");
// Create the Mail Transport Configuration
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername('myemail@gmail.com')
->setPassword('appPassword');
//local domain sending
$transport->setLocalDomain('[127.0.0.1]');
$mailer = Swift_Mailer::newInstance($transport);
//Send the email
$sentFlag = $mailer->send($message);
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>
我正在使用应用密码,并且我已在我的Google帐户设置中启用了两步验证。我一直在寻找这个问题的解决方案一段时间,我已经经历了许多其他相关的帖子,但没有找到解决方案。有人请建议永久解决方案。
提前致谢。
答案 0 :(得分:2)
尝试这样的代码:
<?php
require_once 'lib/swift_required.php';
try
{
echo '<pre>';
//Generating the Email Content
$message = Swift_Message::newInstance()
->setFrom(array('myemail@gmail.com' => 'No Reply'))
->setTo(array('recipient@gmail.com' => 'Recipient'))
->setSubject('Test Email')
->setBody("This is a Test Email to check SwiftMailer.");
// Create the Mail Transport Configuration
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
->setUsername('myemail@gmail.com')
->setPassword('appPassword')
->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' => true,
'verify_peer' => false)));
//local domain sending
$transport->setLocalDomain('[127.0.0.1]');
$mailer = Swift_Mailer::newInstance($transport);
//Send the email
$sentFlag = $mailer->send($message);
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>
希望有所帮助