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...');
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 trying to figure out this issue for 6 hours. But there is nothing to make sense. Here is the scenario; There is a well formatted HTML template.
$mail_body = '
<b>Message Num :</b> 769<br />
<b>Message Date :</b> 2013-04-08 09:03:21<br />
<b>Name :</b> John Doe<br />
<b>Phone :</b> 123456789<br />
<b>E-mail :</b> abcdf#somedomain.com<br />
<b>Message :</b> Here is the message info<br />
';
Here is the array of recipients' mails;
$recipients = array("abc#something.com","xyz#somtehing.com");
Everything looks fine and email ready to send.Here is the phpmailer config;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->From = "noreply#something.com";
$mail->FromName = "TEST";
$mail->WordWrap = 50;
foreach($recipients as $mail_add) {
$mail->AddAddress($mail_add);
}
$mail->IsHTML(true);
$mail->Subject = "TEST Subject";
$mail->Body = $mail_body;
if(!$mail->Send()) {
echo $mail->ErrorInfo;
} else {
echo "Mail sent...";
}
Everything is same when I test it. But sometimes email was sent. Sometimes it was not sent. Give me the following error : The following SMTP Error: Data not accepted.
I hope I explained
your server dosen't allow different sender and username
you should config: $mail->From like $mail->Username
set phpmailer to work in debug to see the "real" error behind the generic message 'SMTP Error: data not accepted' in our case the text in the message was triggering the smtp server spam filter.
$email->SMTPDebug = true;
For AWS users who work with Amazon SES in conjunction with PHPMailer, this error also appears when your "from" mail sender isn't a verified sender.
To add a verified sender:
Log in to your Amazon AWS console: https://console.aws.amazon.com
Select "Amazon SES" from your list of available AWS applications
Select, under "Verified Senders", the "Email Addresses" --> "Verify a new email address"
Navigate to that new sender's email, click the confirmation e-mail's link.
And you're all set.
Interestingly, I had the same exact issue and for me the problem was that my connection was timing out. To be able to see more details on my connections, I added $mail->SMTPDebug = 4; to my phpmailer (look up how to capture the debug since the default output function is echo).
Here's the result:
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is ""
SMTP -> get_lines(): $data is ""
SMTP -> get_lines(): timed-out (10 seconds)
SMTP -> FROM SERVER:
SMTP -> ERROR: DATA not accepted from server:
The default timeout is set to 10 seconds. If your app can support more, add this line to your phpmailer:
$mail->Timeout = 20;
Over a certain message of size, it messes up the content when setting through $mail->Body.
You can test it, if it works well with small messages, but doesn't work with larger (over 4-6 kB), then this is the problem.
It seems to be the problem of $mail->Body, so you can get around this by setting the HTML body manually via $mail->MsgHTML($message). And then you can try to only add the non-html body by $mail->AltBody.
Hope that I could help, feel free to provide more details, information.
I was using just
$mail->Body = $message;
and for some sumbited forms the PHP was returning the error:
SMTP Error: data not accepted.SMTP server error: DATA END command failed Detail: This message was classified as SPAM and may not be delivered
SMTP code: 550
I got it fixed adding this code after $mail->Body=$message :
$mail->MsgHTML = $message;
$mail->AltBody = $message;
Try to set the port on 26, this has fixed my problem with the message "data not accepted".
We send email via the Gmail SMTP servers, and we get this exact error from PHPMailer sometimes when we hit our Gmail send limits.
You can check if it's the same thing happening to you by going into Gmail and trying to manually send an email. In our case that displays the more helpful error message about sending limits.
https://support.google.com/a/answer/166852?hl=en
I was hitting this error with phpMailer + Amazon SES. The phpMailer error is not very descriptive:
2: message: SERVER -> CLIENT: 554 Transaction failed: Expected ';', got "\"
1: message:
2: message: SMTP Error: data not accepted.
For me the issue was simply that I had the following as content type:
$phpmailer->ContentType = 'text/html; charset=utf-8\r\n';
But that it shouldn't have the linebreak in it:
$phpmailer->ContentType = 'text/html; charset=utf-8';
... I suspect this was legacy code from our older version. So basically, triple check every $phpmailer setting you're adding - the smallest detail counts.
First you better set debug to TRUE:
$email->SMTPDebug = true;
Or temporary change value of public $SMTPDebug = false; in PHPMailer class.
And then you can see the full log in the browser.
For me it was too many emails per second:
...
SMTP -> FROM SERVER:XXX.XX.XX.X Ok
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "XXX.XX.XX.X Requested action not taken: too many emails per second "
SMTP -> get_lines(): $data is "XXX.XX.XX.X Requested action not taken: too many emails per second "
SMTP -> FROM SERVER:XXX.XX.XX.X Requested action not taken: too many emails per second
SMTP -> ERROR: DATA command not accepted from server: 550 5.7.0 Requested action not taken: too many emails per second
...
Thus I got to know what was the exact issue.
I was experiencing this same problem. In my instance the send mail was timing out because my Exchange server was relaying email to a server on the internet. That server had exceeded it's bandwidth quota. Apparently php mailer has some built in timeout and it wasn't long enough to see the actual message.
In my case in cpanel i have 'Register mail ids' option where i add my email address and after 30 minutes it works fine with simple php mail function.
If you are using the Office 365 SMTP gateway then "SMTP Error: data not accepted." is the response you will get if the mailbox is full (even if you are just sending from it).
Try deleting some messages out of the mailbox.
In my case the problem was with the content of mail. When I changed content to simpler content without HTML, it worked. But after updating the phpmailer everything solved.
in my case I was using AWS SES and I had to verify both "FromEmail" and "Recipient". Once done that I could send without problems.
Mailgun sanbox error
With $PHPMailer->SMTPDebug = true; I found out that when using the mailgun sandbox domain, the email has to be added to an authorized recipients list (which is on the right panel of the sandbox domain overview)
It happen too, when you used stripslashes or addslashesh or real_escape_string.
Avoid these things inside email body, when your email execution code completed then you can add these lines in bottom.
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.