Swiftmailer with gmail - php

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.

Related

Swiftmailer unable to authenticate to GMail using oauth2 token

I'm trying to use SwiftMailer to log in to a GMail account for which I have a valid access token. I can successfully login using the account credentials:
$Transport = new Swift_SmtpTransport('smtp.gmail.com',587,'tls');
$Transport->setAuthMode('login')
->setUsername('my-email-address')
->setPassword('my-password');
$Mailer = new Swift_Mailer($Transport);
// ... make a new message & send it
However if I change the code to use my oauth2 token like so:
$access_token = 'ya29.GLv....';
$Transport = new Swift_SmtpTransport('smtp.gmail.com',587,'tls');
$Transport->setAuthMode('XOAUTH2')
->setUsername('my-email-address')
->setPassword($access_token);
$Mailer = new Swift_Mailer($Transport);
I get an error message: Swift_TransportException: Expected response code 250 but got code "535".... Username and Password are not accepted.
I'm using the same access token elsewhere using the GMail API, so I know the token is valid.
What am I missing?
Edit
Just ran the code again with the debugger turned on. It looks like the first error code thrown is 334 with the message:
Expected response code 235 but got code "334", with message "334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
The encoded part of that message decodes to:
{"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"}
The biggest hurdle that you might face and no one is talking about is insufficient permissions. SwiftMailer doesn't do a good job elaborating this issue; therefore you might want to use GoogleClient to make sure you credentials are working before using them with SwiftMailer.
Full source code
# Using SwiftMailer
// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls'))
->setAuthMode('XOAUTH2')
->setUsername('<SENDER_EMAIL>')
->setPassword('<ACCESS_TOKEN>');
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = (new Swift_Message())
->setFrom(['<SENDER_EMAIL>' => '<SENDER_NAME>'])
->setTo(explode(';', '<RECEIVER_EMAIL>'))
->setSubject('<SUBJECT')
->setBody('<MESSGAE_BODY>');
// Send the message
if ($mailer->send($message)) {
print 'Mail sent...';
exit();
}
echo('Mail not sent...');

swiftmailer Auth issues with hotmail

I've searched high and low and I can't seem to find a working example of a swiftmailer script that uses a hotmail smtp, I have tried using the google one's in examples and upating the port, user and password but the page just hangs until it times out.
My code:
require_once 'lib/swift_required.php';
// Create the SMTP configuration
$transport = Swift_SmtpTransport::newInstance("smtp.live.com", 465, "TLS");
$transport->setUsername("xxxx#hotmail.com");
$transport->setPassword("XXXXXX");
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
"XXXX#company.com" => "xxx",
));
$message->setCc(array("another#fake.com" => "Aurelio De Rosa"));
$message->setBcc(array("boss#bank.com" => "Bank Boss"));
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You're our best client ever.");
$message->setFrom("XXXXX", "XX XXXXXXX");
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message, $failedRecipients);
// Show failed recipients
print_r($failedRecipients);
I expect you need to set your encryption param correctly. For port 465 use ssl; for 587, tls. hotmail isn't any different to anywhere else - your code would not work anywhere.

Why I have this error with swift mail php

I have configured SwiftMailer with theses params but when I try to send a mail I have an error.
Code:
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587,'tls')
->setUsername('mail#gmail.com')
->setPassword('password');
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
Swift::init('swiftmailer_configurator');
// Create the message
$message = Swift_Message::newInstance()
// Give the message a subject
->setSubject($sujet)
// Set the From address with an associative array
->setFrom(array('Mail#mail.com' => 'Site Mail'))
// Set the To addresses with an associative array
->setTo(array($mail))
// Give it a body
->setBody($texte)
// And optionally an alternative body
->addPart("<q>$texte</q>", 'text/html');
// Send the message
if ($mailer->send($message)) {
echo "Sent";
} else {
echo "Failed";
}
Result:
Fatal error: Uncaught exception 'Swift_TransportException' with
message ' in
C:\wamp\www\mail\swiftmailer\lib\classes\Swift\Transport\AbstractSmtpTransport.php
on line 383 ( ! ) Swift_TransportException: Expected response code 250
but got code "535", with message "535-5.7.8 Username and Password not
accepted. Learn more at 535 5.7.8
https://support.google.com/mail/answer/14257 e69sm88886wma.2 - gsmtp "
in
C:\wamp\www\mail\swiftmailer\lib\classes\Swift\Transport\AbstractSmtpTransport.php
on line 383
As the error message says,
535-5.7.8 Username and Password not accepted
You need to authorize the use of Gmail for external applications: go to https://www.google.com/settings/security/lesssecureapps then change Access for less secure apps to enabled.
If it's still not working, you can follow the advises given on this page.
Ok, I solved my problem by using my pro mail istead of my personal mail

SwiftMailer + Gmail - Cannot send email

I can't connect with Gmail SMTP server.
Look:
$transport = Swift_SmtpTransport::newInstance()
->setHost('smtp.gmail.com')
->setPort(465)
->setEncryption('ssl')
->setUsername('email#gmail.com')
->setPassword('mypasss');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Contato via Site')
->setFrom(array($email => $de))
->setTo(array($destinatario => 'AgĂȘncia Linka'))
->setBody($corpo_mensagem, 'text/html')
->setCharset('UTF-8');
$mailer->send($message);
And then I get this:
Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [ #0]' in ...
Anyone has experienced this?
First login with your account and open this in new tab,
https://www.google.com/settings/u/1/security/lesssecureapps
https://accounts.google.com/b/0/DisplayUnlockCaptcha
https://security.google.com/settings/security/activity?hl=en&pli=1
you need to make sure your using email id has enable for less secure apps.
You can send mail by using tls instead of ssl certificate like below:
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587,'tls')
->setUsername('email#gmail.com')
->setPassword('mypasss');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Contato via Site')
->setFrom(array($email => $de))
->setTo(array($destinatario => 'AgĂȘncia Linka'))
->setBody($corpo_mensagem, 'text/html')
->setCharset('UTF-8');
$mailer->send($message);
Gmail has changed his policy so yuo will need to take special additional steps to make this working, I could explain it here for you but You can have a look at this answer which explains the action you need to take:
Using php's swiftmailer with gmail

Swiftmailer Erroring Out

I'm having some trouble with swiftmailer. It keeps crashing on me, but if I take out the ->sentTo it doesn't error out but I also can't receive an Email.
I'm confused as to what I am doing wrong.
require_once 'lib/swift_required.php';
// Using smtp
//$transport = Swift_SmtpTransport::newInstance('my_smtp_host.com', 25)
//Using Gmail
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername('***') // or your gmail username
->setPassword('***'); // or your gmail password
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance($subject)
->setFrom(array($email => $name))
->setTo(array('John.Doe#gmail.com' => 'John Doe'))
->setBody($content, 'text/html');
$message->attach(
Swift_Attachment::fromPath($_FILES['userfile']['name'])->setFilename($pic['tmp_name'])
);
// Send the message
$result = $mailer->send($message);
?>
Fatal error:
Uncaught exception 'Swift_TransportException' with message 'Failed to authenticate on SMTP server with username "...." using 2 possible authenticators' in ../lib/classes/Swift/Transport/Esmtp/AuthHandler.php:184
Stack trace:
0 ../lib/classes/Swift/Transport/Esmtp/EsmtpTransport.php(312): Swift_Transport_Esmtp_AuthHandler->afterEhlo(Object(Swift_SmtpTransport))
1 ../lib/classes/Swift/Transport/AbstractSmtpTransport.php(120): Swift_Transport_EsmtpTransport->_doHeloCommand()
2 ../lib/classes/Swift/Mailer.php(80): Swift_Transport_AbstractSmtpTransport->start()
3 upload.php(73): Swift_Mailer->send(Object(Swift_Message))
4 {main} thrown in lib/classes/Swift/Transport/Esmtp/AuthHandler.php on line 184
Had to change the message attachment to this:
$message->attach(
Swift_Attachment::fromPath($theDirectory)->setFilename($fileNameForEmail)
);
// Send the message
$result = $mailer->send($message);
}
else{
echo 'The file you have chosen is invalid. Please go back and try again.';
}
This:
Failed to authenticate on SMTP server with username "...." using 2
possible authenticators
... means exactly what it says. Gmail did not accept your username and password, either because they are wrong or because you failed to provide some required parameter.
Host name, port and encryption are correct according to other questions at Stack Overflow and my own tests. So probably issues include:
You provided an incorrect user name.
You provided an incorrect password.
If you've enabled two-way authentication, you need to generate an application specific password. This video explains how.
Once you fix this, you'll probably get the following exception:
Uncaught exception 'Swift_IoException' with message 'Unable to open file for reading []'
... triggered by this code:
Swift_Attachment::fromPath($_FILES['userfile']['name'])
The reason if that you are reading the wrong item from the $_FILES array: fromPath() expects a file system path to read but $_FILES['userfile']['name'] contains the original name of the file on the client machine.

Categories