Email not being sent with Swift Mailer using Gmail SMTP - php

I am trying to send emails from Swift Mailer using Gmail SMTP. It sends the emails conveniently for some time but then stops sending them altogether especially when I resume working after a day or so. It displays the following error:
Connection could not be established with host smtp.gmail.com [ #0]
Below is my sample code that I am using to send the email:
<?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();
}
?>
I am using App Password and I have enabled two-step verification in my Google Account Settings. I have been looking for a solution to this problem for a while now and i have already gone through many other related posts but didn't find a solution. Someone please suggest a permanent solution.
Thanks in advance.

How to use Swift Mailer Using Gmail SMTP
Try this code like this:
<?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();
}
?>
Hope it helps

Related

Swiftmailer Gateway timeout error

I am getting Gateway timeout error when using swiftmailer on hosted server. But on my PC localhost, its works fine.
When I informed to my hosting, they said they have enabled the outbound connection to port no 465.
Script I have used.
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
require_once 'mailer/lib/swift_required.php';
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername('myemail#gmail.com')
->setPassword('myapppassword')
;
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance()
->setSubject('New Message From ' . $name)
->setFrom(array($email => '$name'))
->setReplyTo($email)
->setTo(array('myemail#gmail.com' => 'My Name'))
->setBody($message)
->addPart('Message: <b>'. $message .'</b>', 'text/html')
;
$result = $mailer->send($message);
if(!$result) {
echo $msg = 'Oops. Something went wrong. Please try again later.';
} else {
echo $msg = 'Thank you. Your query has been submitted. We will contact you back through the provided email address.';
}
Above code used only for hiding headers. But headers are used in order to direct.

Using SMTP PHPMailer for 'Domain' email address, email sent but not recieved

I am using PHPMailer to send email. It works fine when I use gmail smtp but when I try using my domain smtp what I see on screen is 'message sent!' but I don't receive any email at all. I have tried using debugger, it says
We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
and here is my code
<?php
date_default_timezone_set('Etc/UTC');
//Load PHPMailer dependencies
require_once 'PHPMailerAutoload.php';
require_once 'class.phpmailer.php';
require_once 'class.smtp.php';
/* CONFIGURATION */
$crendentials = array(
'email' => 'xxxxx#example.com',
'password' => 'xxxxxx'
);
$smtp = array(
'host' => 'secure.ehostpk.com',
'port' => 465,
'username' => $crendentials['email'],
'password' => $crendentials['password'],
'secure' => 'ssl' //SSL or TLS
);
/* TO, SUBJECT, CONTENT */
$to = 'xxxxxx#example.com'; //The 'To' field
$subject = 'This is a test email sent with PHPMailer';
$content = 'This is the HTML message body <b>in bold!</b>';
$mailer = new PHPMailer();
//SMTP Configuration
$mailer->isSMTP();
$mailer->SMTPDebug = 2;
$mailer->SMTPAuth = true; //We need to authenticate
$mailer->Host = $smtp['host'];
$mailer->Port = $smtp['port'];
$mailer->Username = $smtp['username'];
$mailer->Password = $smtp['password'];
$mailer->SMTPSecure = $smtp['secure'];
//Now, send mail :
//From - To :
$mailer->From = $crendentials['email'];
$mailer->FromName = 'Team'; //Optional
$mailer->addAddress($to); // Add a recipient
//Subject - Body :
$mailer->Subject = $subject;
$mailer->Body = $content;
$mailer->isHTML(true); //Mail body contains HTML tags
//Check if mail is sent :
if(!$mailer->send()) {
echo 'Error sending mail : ' . $mailer->ErrorInfo;
} else {
echo 'Message sent !';
}
I have searched a lot and I don't understand what should I do. Any help would be greatly appreciated.
One thing that I have found is, that on most servers these days (especially cpanel servers) the email address you are attempting to send with actually has to be created within cpanel itself in order for it to work properly.
From my understanding, the script only routes it to the server and the email account, and then it's routed further from there and finally sent out from your email account on the server. So a solution may be to actually setup the email address in your server.

SwiftMailer Error

So I am trying to setup swift mailer to work with the Mandrill API, but it keeps throwing the following error:
Failures:Array ( [0] => example#email.com ) (I have a proper email in this place in my code)
My code is as follows:
$subject = 'Hello from Mandrill, PHP!';
// approved domains only!
$from = array('example2#email.com' =>'Your Name');
$to = array(
'example#email.com' => 'Recipient1 Name'
);
$text = "Mandrill speaks plaintext";
$html = "Mandrill speaks HTML";
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587);
$transport->setUsername(getenv('my#mandrillemail.com'));
$transport->setPassword(getenv('mymandrillpass'));
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
// Pass a variable name to the send() method
if (!$swift->send($message, $failures))
{
echo "Failures:";
print_r($failures);
}
What is going wrong?
Try using SSL and port 465.
$xport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 465, 'ssl');
$xport->setUsername('mandrilluser')
->setPassword('mandrillpass');
See if this works for you.
My problem ended up being that I had to change from using the actual Mandrill account password to the API in the ->setPassword() variable.
Since this is purely an error with your credentials, cross check if the password you are using is actually the token generated by Mandrill or not .
Password doesn't mean the 'password' of your account !!

PHP SwiftMailer Not sending

I am doing some testing prior to working on some production code and need to figure out how to do an auto e-mail.
The below script runs fine and the result of the send method returns 1, as if it sends. However, nothing ever makes it to the recipient.
require_once '/home/absolut2/lib/swift_required.php';
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('mail.mysite.com', 25)
->setUsername('myuser')
->setPassword('password')
;
/*
You could alternatively use a different transport such as Sendmail or Mail:
//Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
//Mail
$transport = Swift_MailTransport::newInstance();
*/
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
//Create a message
$message = Swift_Message::newInstance('Subject')
->setFrom(array('rp#mysite.com' => 'RP'))
->setTo(array('rp#gmail.com'))
->setBody('Here is the message itself');
//Send the message
$result = $mailer->send($message);
echo "Messages sent: " . $result;
The code itself seems fine, so I guess something else is wrong. Either check the spam queue of the recipient or maybe just the address was rejected.
Find out if addresses were rejected.
You can do that with this code:
if (!$mailer->send($message, $failures)) {
echo "Failures:";
print_r($failures);
}

trying to send mail using swift mailer, gmail smtp, php

Here is my code:
<?php
require_once 'Swift/lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465)
->setUsername('me#ff.com')
->setPassword('pass');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('me#ff.com' => 'MY NAME'))
->setTo(array('you#ss.com' => 'YOU'))
->setBody('This is the text of the mail send by Swift using SMTP transport.');
//$attachment = Swift_Attachment::newInstance(file_get_contents('path/logo.png'), 'logo.png');
//$message->attach($attachment);
$numSent = $mailer->send($message);
printf("Sent %d messages\n", $numSent);
?>
AFter RUNNING GOT THIS ERROR...
Fatal error: Uncaught exception 'Swift_TransportException' with message 'Expected response code 220 but got code "", with message ""' in /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php:406
Stack trace:
#0 /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php(299): Swift_Transport_AbstractSmtpTransport->_assertResponseCode('', Array)
#1 /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php(107): Swift_Transport_AbstractSmtpTransport->_readGreeting()
#2 /home/sitenyou/public_html/Swift/lib/classes/Swift/Mailer.php(74): Swift_Transport_AbstractSmtpTransport->start()
#3 /home/sitenyou/public_html/sgmail.php(16): Swift_Mailer->send(Object(Swift_Message))
#4 {main} thrown in /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php on line 406
GMail's SMTP requires encryption. Use:
Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl");
there is missing the ssl parameter, it should be something like that
Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
Tested and work fine
Swift SmtpTransport - Code (send a email)
The SMTP of GMAIL is: smtp.googlemail.com
The Full Code:
<?php
$pEmailGmail = 'xxxx#gmail.com';
$pPasswordGmail = '********';
$pFromName = 'MundialSYS.com'; //display name
$pTo = 'xxxxxx#xxxx.xxx'; //destination email
$pSubjetc = "Hello MundialSYS"; //the subjetc
$pBody = '<html><body><p>Hello MundialSYS</p></html></body>'; //body html
$transport = Swift_SmtpTransport::newInstance('smtp.googlemail.com', 465, 'ssl')
->setUsername($pEmailGmail)
->setPassword($pPasswordGmail);
$mMailer = Swift_Mailer::newInstance($transport);
$mEmail = Swift_Message::newInstance();
$mEmail->setSubject($pSubjetc);
$mEmail->setTo($pTo);
$mEmail->setFrom(array($pEmailGmail => $pFromName));
$mEmail->setBody($pBody, 'text/html'); //body html
if($mMailer->send($mEmail) == 1){
echo 'send ok';
}
else {
echo 'send error';
}
?>
I cannot be sure, but I think that Gmail's port is 587 using TLS, which is not SSL, but a newer version of it. You should check into that, because I think you are placing the wrong construction code.
Best of luck!
I have managed to get this working without the SSL, here is how:
$transport = Swift_SmtpTransport::newInstance('tls://smtp.gmail.com', 465)
->setUsername('contact#columbussoft.com')
->setPassword('password');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance($subject)
->setFrom(array($emailTo=>$name))
->setTo(array($emailTo=>'Neo Nosrati'))
->addPart($body,'text/plain')
->setReturnPath('other#columbussoft.com');
I'm using the "Messages Swift Mailer" bundle in Laravel 3 and having the same issue. After some testing, in my case, the solution was to set the same email address that I used in the SMTP authentication on the "from" parameter.
I was trying to use a different address and that was triggering the "swiftmailer expected response code 220 but got code with message" error.
Hope that helps.
I got same error before and i added "ssl" parameter in Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl") like osos said.
IT WORKS!! thanks..:D
this is my code:
<?php
require_once 'swift/lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername('XXXXXXX#gmail.com')
->setPassword('XXXXXXX');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('THIS IS THE SUBJECT')
->setFrom(array('XXXXXXX#gmail.com' => 'YOUR NAME'))
->setTo(array('XXXXXXX#gmail.com' => 'YOU'))
->setBody('This is the text of the mail send by Swift using SMTP transport.');
//$attachment = Swift_Attachment::newInstance(file_get_contents('path/logo.png'), 'logo.png');
//$message->attach($attachment);
$numSent = $mailer->send($message);
printf("Sent %d messages\n", $numSent);
?>
For google apps, in addition to setting to port 465 and ssl as recommended in the accepted answer, you may have to enable allow less secure apps setting, as per https://stackoverflow.com/a/25238515/947370

Categories