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...');
Related
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
I am teaching myself php and how to use Swiftmailer. I have followed the doc and added the code below to my php file, but it returns array( ). I can't figure out what could be wrong and how to check. I don't seem to have access to the remote server's ini file from the hosting provider. Would appreciate any help in determining what may be wrong and how to correct. thanks!
require_once 'Swift/lib/swift_required.php';
//Use simple mail transport
$transport = Swift_MailTransport::newInstance();
// Create the message
$message = Swift_Message::newInstance();
$message->setTo("xxx#yyy.com");
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You're our best client ever.");
//$message->setFrom($email);
$message->setFrom("xxx#zzz.net");
$message->setReturnPath('xxx#zzz.net');
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message, $failedRecipients);
// Show failed recipients
print_r($failedRecipients);
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
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.
I'm getting this error when trying to send an email using swiftmailer and the sendgrid smtp
Fatal error: *Uncaught exception 'Swift_TransportException' with message 'Expected response code 250 but got code "", with message ""'*
Here's my code :
$hdr = new SmtpApiHeader();
// Set all of the above variables
$hdr->addTo($toList);
$hdr->addSubVal('-name-', $nameList);
$hdr->addSubVal('-time-', $timeList);
// Specify that this is an initial contact message
$hdr->setCategory("initial");
// The subject of your email
$subject = 'Example SendGrid Email';
// Where is this message coming from. For example, this message can be from
// support#yourcompany.com, info#yourcompany.com
$from = array('no-reply#mupiz.com' => 'Mupiz');
$to = array('antonin#noos.fr'=>'AN',"antonin#mupiz.com"=>"AN2s");
$text="Hello -name-
Thank you for your interest in our products. We have set up an appointment
to call you at -time- EST to discuss your needs in more detail.
Regards,
Fred, How are you?
";
$html = "
<html>
<head></head>
<body>
<p>Hello -name-,<br>
Thank you for your interest in our products. We have set up an appointment
to call you at -time- EST to discuss your needs in more detail.
Regards,
Fred, How are you?<br>
</p>
</body>
</html>
";
// Your SendGrid account credentials
$username = 'XXXX';
$password = 'XXXX';
// Create new swift connection and authenticate
$transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 25);
$transport ->setUsername($username);
$transport ->setPassword($password);
$swift = Swift_Mailer::newInstance($transport);
// Create a message (subject)
$message = new Swift_Message($subject);
// add SMTPAPI header to the message
// *****IMPORTANT NOTE*****
// SendGrid's asJSON function escapes characters. If you are using Swift Mailer's
// PHP Mailer functions, the getTextHeader function will also escape characters.
// This can cause the filter to be dropped.
$headers = $message->getHeaders();
$headers->addTextHeader('X-SMTPAPI', $hdr->asJSON());
// attach the body of the email
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
// send message
if ($recipients = $swift->send($message, $failures))
{
// This will let us know how many users received this message
// If we specify the names in the X-SMTPAPI header, then this will always be 1.
echo 'Message sent out to '.$recipients.' users';
}
// something went wrong =(
else
{
echo "Something went wrong - ";
print_r($failures);
}
An idea ?
Thanks
There could be a number of things causing this. The most likely one is that your server has connecting to external hosts turned off. Other possibilities are that you're using an old version of PHP that has an openSSL error or that you're being rate limited by something.
You should take a look at this question for details on the external host issue: send mails via sendgrid
On a separate note, you should use the SendGrid PHP library if you want to send emails using SendGrid. It addresses a whole bunch of subtle nuances with Swift and sending in general. Also, it gives you access to the HTTP API in case you can't use SMTP for whatever reason.
https://github.com/sendgrid/sendgrid-php
Full Disclosure: I work as a developer evangelist for SendGrid and work on the PHP library from time to time.
for sendgrid might be two resons:
you may have the authentification data wrong
your account might still be provisioned, so you must wait a bit for it to be fully activated
so
check all the autentification data from app/config/mail.php to match with the data from https://sendgrid.com/docs/Integrate/index.html
check also not the have a top message/notification on your sendgrid account like:
Your account is still being provisioned, you may not be able to send
emails.
You will also receive this error if your account is frozen for billing reasons (e.g. lapsed credit card expiry date).
Note: SendGrid doesn't drop the message(s), they hold them until your billing issue is resolved then process them even when this error is returned.