简体   繁体   中英

Swiftmailer with gmail

So I am trying to use swiftmailer to send emails using a gmail account. I know there are questions that address this issue, but none of the proposed solutions have helped me. My problem is that when I run my code I get "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." I know that my password and username are correct, and the Google two-step verification is not enabled. Here is my code:

require_once 'vendor/swiftmailer/swiftmailer/lib/classes/Swift.php'; Swift::registerAutoload();

require_once 'vendor/swiftmailer/swiftmailer/lib/swift_required.php';
require_once 'vendor/swiftmailer/swiftmailer/lib/swift_init.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
    ->setUsername ('myemail@gmail.com')
    ->setPassword ('mypassword');

$mailer = Swift_Mailer::newInstance($transport);    

$message = Swift_Message::newInstance('Weekly Hours')
    ->setFrom (array('myemail@gmail.com' => 'My Name'))
    ->setTo (array('recipient@hotmail.com' => 'Recipient'))
    ->setSubject ('Weekly Hours')
    ->setBody ($data, 'text/html');

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

Note that I have also tried port 465 with 'lss' encryption. Thanks in advance.

The problem could be related to the fact that google can use a range of IPs.

I solved the problem in my case with something like this:

 #get the host dynamically
 $smtp_host_ip = gethostbyname('smtp.gmail.com');

 #set the transport
 $transport = Swift_SmtpTransport::newInstance($smtp_host_ip,465,'ssl')->setUsername('myemail@gmail.com')->setPassword('mypassword');

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM