i have been working on php7 upgrade and also moved phpmailer to be loaded via composer.
we have a build system that is tested on Travis. we use grunt to run selenium tests.
when i test locally (grunt test) all tests pass, but when i push to Travis (via GitHub) there are some tests that are failing.
tests that fail return following message (in Travis log after setting SMTPDebug to 3):
2018-06-27 12:39:23 Connection: opening to smtp.sendgrid.net:587, timeout=300, options=array()
2018-06-27 12:43:37 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.sendgrid.net:587 (Connection timed out) [/var/www/includes/phpmailer/phpmailer/src/SMTP.php line 325]
2018-06-27 12:43:37 SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
strange thing is that there are some passing tests that use the same code as failing tests. we instantiate our wrapper object with the same attributes in each of the scripts that are sending mail.
this is the except from the code that is failing to send mail:
$mail->sendMsg($config->getOpt('site_name'),
$config->getOpt('site_email'),
$userInfo['userName'],
$userInfo['userEmail'],
Strings::strPad(_('Purchase confirmation from'),1,' ',STR_PAD_RIGHT) . $config->getOpt('site_name'),
$boostPurchaseConfirmMsg,
nl2br($boostPurchaseConfirmMsg));
this is the except from the the code that is sending mail:
$mail->sendMsg($config->getOpt('site_name'),
$config->getOpt('site_email'),
$_POST['userEmail'],
$_POST['userEmail'],
Strings::strPad(_('Welcome to')) . $config->getOpt('site_name') . '!',
$registerMsg,
nl2br($registerMsg));
this is the function within our wrapper object that is actually sending mails:
public function sendMsg($fromName, $fromEmail, $toName, $toEmail, $subject, $messageText, $messageHTML = null, $CCs = null)
{
$mail = new PHPMailer(true);
if (false === $mail) {
throw new gException('No PHPMailer object available');
}
try {
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 3;
$mail->Host = $this->host; // Specify main and backup SMTP servers
$mail->Port = $this->port;
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $this->username; // SMTP username
$mail->Password = $this->password; // SMTP password
$mail->SMTPSecure = 'tls';
$mail->From = $fromEmail;
$mail->FromName = $fromName;
$mail->addAddress($toEmail, $toName); // Add a recipient
$mail->addReplyTo($fromEmail, $fromName);
if (null !== $CCs) {
if (is_array($CCs)) {
foreach ($CCs AS $cc) {
$mail->addBCC($cc);
}
} else {
$mail->addBCC($CCs);
}
}
$mail->WordWrap = 50;
$mail->isHTML(true);
if (strlen($messageText) < 1) {
$messageText = $messageHTML;
}
if (strlen($messageHTML) < 1) {
$messageHTML = $messageText;
}
$mail->Subject = $subject;
$mail->Body = nl2br($messageHTML);
$mail->AltBody = strip_tags($messageText);
return $mail->send();
} catch (PHPMailerException $e) {
throw new gException('PHPMailer exception message : ' . $e->errorMessage());
}
}
please help. i have already tried setting mock smtp service on Travis, but it doesn't matter. i reviewed if we are using correct port. i did all the things that phpmailer wiki suggest to try troubleshooting.
i repeat tests are passing locally, so everything is working. Travis is holding me hostage.
UPDATE
this might seem misleading, the solution, as it turns out, was to not check PHPMailer success on sending mails. we had the agreement that we will not inform the user that mails are not sent, since they are only informative, instead we will be logging exceptions for further analysis.
do not test mail success on travis, it will fail. travis doesn't allow outbound SMTP traffic.
use the strategies proposed by the PHPMailer troubleshooting wiki.
thank you #Syncro
I am trying to send an email using Mailer but getting below error
Connection: opening 2017-05-25 08:22:07 SMTP ERROR: Failed to connect
to server: (0) SMTP connect() failed. Mailer Error: SMTP connect()
failed.
php_openssl extension & IMAP both are enabled. I tried to find it on google but still no luck.
Code:
function sendMail($subject='',$to='',$emailcontent='',$attach='')
{
global $_mailmsg;
//echo $emailcontent;exit;
$mail = new PHPMailer;
$mail->SMTPDebug = 4;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = '465';
$mail->SMTPAuth = true;
$mail->Username = 'xx#gmail.com';
$mail->Password = 'xxxx';
$mail->SMTPSecure = 'ssl';
$mail->From = 'xx#gmail.com';
$mail->FromName = 'Test';
$mail->addAddress($to); // Add a recipient
if(!empty($cc)){ $mail->addCC($cc); }
if(!empty($bcc)){ $mail->addBCC($bcc); }
$mail->WordWrap = 50;
if($attach != ''){
$mail->addAttachment($attach);
}
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = 'Test';
try
{
if($mail->send()) {
return 1;
exit;
}
else
{
echo 'Mailer Error: ' . $mail->ErrorInfo;
return 0;
}
}
catch(Exception $e)
{
return 0;
}
}
This looks like your server is not permitted to connect to remote SMTP servers, something very common at big ISPs like GoDaddy. If you do the steps described in the troubleshooting guide you can figure out what's blocking you. The fact that there is no link to the guide in your error message tells me that you're using a very old version of PHPMailer, so get the latest.
PHPMailer has nothing to do with IMAP; that's for inbound mail only.
As you are using Gmail, just turn on "Allow less secure apps":
https://myaccount.google.com/u/0/lesssecureapps
And also you'll probably need to allow access to your Google account without unlock captcha:
https://accounts.google.com/DisplayUnlockCaptcha
I've been running PHPMailer for a year now on a php server. Everything was fine until 3 days ago when I started getting the following error:
SMTP Error: Could not authenticate.
Allow less secure apps is ON
Here is the code:
function SendEmail($to,$cc,$bcc,$subject,$body) {
require 'PHPMailerAutoload.php';
$mail = new PHPMailer(true);
$mail->SMTPDebug = 1;
try {
$addresses = explode(',', $to);
foreach ($addresses as $address) {
$mail->AddAddress($address);
}
if($cc!=''){
$mail->addCustomHeader("CC: " . $cc);
}
if($bcc!=''){
$mail->addCustomHeader("BCC: " . $bcc);
}
$mail->IsSMTP();
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587;
$mail->Username = "myemail#gmail.com"; // SMTP username
$mail->Password = "myemailpass"; // SMTP password
$webmaster_email = "myemail#gmail.com"; //Reply to this email ID
$name=$email;
$mail->From = $webmaster_email;
$mail->FromName = "Service";
//$mail->AddReplyTo($webmaster_email, "DiFractal Customer Service");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = $subject;
$mail->Body = $body;
return $mail->Send();
} catch (phpmailerException $e) {
$myfile = fopen("debug_email.txt", "w");
fwrite($myfile,$e->errorMessage() . "\n" . $mail->ErrorInfo);
fclose($myfile);//Pretty error messages from PHPMailer
} catch (Exception $e) {
$myfile = fopen("debug_email_stp.txt", "w");
fwrite($myfile,$e->getMessage());
fclose($myfile);//Pretty error messages from PHPMailer
}
}
Note I just updated PHPMailer to the latest version to try to remedy the problem but nothing has changed! The old version 5.2.2 was still having the same problem!
EDIT: I just had one successful email go through to google and sent properly. Which now makes me question if it's lag issue or something of that sort. Does anyone know how phpmailer functions under high loads or if high loads can cause the above error?
Try going to:
myaccount.google.com -> "connected apps & sites", and turn "Allow less secure apps" to "ON".
Alternative:
Try changing SMTP Port to: 465 (gmail also).
I was having similar issues and needed to set the from address
$mail->setFrom('myemail#gmail.com', 'Webmaster');
Make sure you check google's usage limits! PHPMailer will not tell you particulars it will just give you the Could not authenticate error but the reason why can be because of your limits.
# https://support.google.com/a/answer/166852?hl=en
Upgraded to a new account with google business and switched to that account. Issue resolved.
I am new to PHP. I was trying to send myself a sample e-mail through PHPmailer. I am using gmail's smtp server. I am trying to send a sample mail from my gmail account to my yahoo account. But I am getting the error : Mailer Error: SMTP connect() failed.
Here is the code :
<?php
require "class.phpmailer.php";
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "ssl://smtp.gmail.com";
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "myemail#gmail.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
$webmaster_email = "myemail#gmail.com"; //Reply to this email ID
$email="myyahoomail#yahoo.in"; // Recipients email ID
$name="My Name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->Port = 465;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
I am using WAMP server on a Windows 7 64-bit machine. What could be the prob?
Please help me solve this. Thanks!
The solution of this problem is really very simple. actually Google start using a new authorization mechanism for its User.. you might have seen another line in debug console prompting you to log into your account using any browser.! this is because of new XOAUTH2 authentication mechanism which google start using since 2014.
remember.. do not use the ssl over port 465, instead go for tls over 587. this is just because of XOAUTH2 authentication mechanism. if you use ssl over 465, your request will be bounced back.
what you really need to do is .. log into your google account and open up following address
https://www.google.com/settings/security/lesssecureapps
and check turn on . you have to do this for letting you to connect with the google SMTP because according to new authentication mechanism google bounce back all the requests from all those applications which does not follow any standard encryption technique.. after checking turn on.. you are good to go..
here is the code which worked fine for me..
require_once 'C:\xampp\htdocs\email\vendor\autoload.php';
define ('GUSER','youremail#gmail.com');
define ('GPWD','your password');
// make a separate file and include this file in that. call this function in that file.
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->SMTPAutoTLS = false;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
You need to add the Host parameter
$mail->Host = "ssl://smtp.gmail.com";
Also, check if you have open_ssl enabled.
<?php
echo !extension_loaded('openssl')?"Not Available":"Available";
Solved an almost identical problem, by adding these lines to the standard PHPMailer configuration. Works like a charm.
$mail->SMTPKeepAlive = true;
$mail->Mailer = “smtp”; // don't change the quotes!
Came across this code (from Simon Chen) while researching a solution here, https://webolio.wordpress.com/2008/03/02/phpmailer-and-smtp-on-1and1-shared-hosting/#comment-89
Troubleshooting
You have add this code:
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
And Enabling Allow less secure apps:
"will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"
This work for me!
$mail->SMTPKeepAlive = true;
$mail->isSendMail(); // instead of isSMTP();
On shared hosting, your mail server may occasionally experience connection issues.
Here I found solution
[Edit]
Here is the link content, in case the link stop working for some reason (it happens)
PHPMailer and SMTP on 1and1 shared hosting
I use PHPMailer on my 1and1 shared hosting account. Recently, I could not send email anymore.
I tried debugging and this is the error that PHPMailer throws:
Language string failed to load: connect_host
After googling for a solution and trying different SMTP servers, accounts and SMTP ports, I decided to switch to sendmail and it worked like a charm! All I needed to do was to replace $mail->isSmtp() with:
$mail->isSendMail()
sendMail is located in its default location on 1and1 servers : /usr/sbin/sendmail, so no change of settings was required.
Conclusion:
1and1 probably closed its outgoing SMTP ports on its shared hosting servers. Consequently, if you use PHPMailer, don’t use SMTP mode anymore.
If anyone is still unable to solve the issue, please check following thread and follow callmebob's answer.
PHPMailer - SMTP ERROR: Password command failed when send mail from my server
I fixed it ...
https://github.com/PHPMailer/PHPMailer/tree/5.2-stable
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'm7#gmail.com'; // SMTP username
$mail->Password = 'pass'; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25; // TCP port to connect to
$mail->setFrom('m7#gmail.com', 'Mailer');
$mail->addAddress('dot#gmail.com', 'User'); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Turn on access and enjoy..! That is on Gmail account setting.
You are missing the directive that states the connection uses SSL
require ("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; // turn of SMTP authentication
$mail->Username = "YAHOO ACCOUNT"; // SMTP username
$mail->Password = "YAHOO ACCOUNT PASSWORD"; // SMTP password
$mail->SMTPSecure = "ssl";
$mail->Host = "YAHOO HOST"; // SMTP host
$mail->Port = 465;
Then add in the other parts
$webmaster_email = "myemail#gmail.com"; //Reply to this email ID
$email="myyahoomail#yahoo.in"; // Recipients email ID
$name="My Name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
As a side note, I have had trouble using Body + AltBody together although they are supposed to work. As a result, I wrote the following wrapper function which works perfectly.
<?php
require ("class.phpmailer.php");
// Setup Configuration for Mail Server Settings
$email['host'] = 'smtp.email.com';
$email['port'] = 366;
$email['user'] = 'from#email.com';
$email['pass'] = 'from password';
$email['from'] = 'From Name';
$email['reply'] = 'replyto#email.com';
$email['replyname'] = 'Reply To Name';
$addresses_to_mail_to = 'email1#email.com;email2#email.com';
$email_subject = 'My Subject';
$email_body = '<html>Code Here</html>';
$who_is_receiving_name = 'John Smith';
$result = sendmail(
$email_body,
$email_subject,
$addresses_to_mail_to,
$who_is_receiving_name
);
var_export($result);
function sendmail($body, $subject, $to, $name, $attach = "") {
global $email;
$return = false;
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = $email['host']; // SMTP server
// $mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = $email['host']; // sets the SMTP server
$mail->Port = $email['port']; // set the SMTP port for the GMAIL server
$mail->SMTPSecure = "tls";
$mail->Username = $email['user']; // SMTP account username
$mail->Password = $email['pass']; // SMTP account password
$mail->AddReplyTo($email['reply'], $email['replyname']);
if(stristr($to,';')) {
$totmp = explode(';',$to);
foreach($totmp as $destto) {
if(trim($destto) != "") {
$mail->AddAddress(trim($destto), $name);
}
}
} else {
$mail->AddAddress($to, $name);
}
$mail->SetFrom($email['user'], $email['from']);
$mail->Subject = $subject;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
if(is_array($attach)) {
foreach($attach as $attach_f) {
if($attach_f != "") {
$mail->AddAttachment($attach_f); // attachment
}
}
} else {
if($attach != "") {
$mail->AddAttachment($attach); // attachment
}
}
$mail->Send();
} catch (phpmailerException $e) {
$return = $e->errorMessage();
} catch (Exception $e) {
$return = $e->errorMessage();
}
return $return;
}
if everything fails then for gmail you must turn on access to 3rd party apps to connect to ur gmail account.
https://www.google.com/settings/security/lesssecureapps // turn it
on
Just make sure you passed the right parameters
eg. the correct outgoing server host, username, and password
$mail->SMTPDebug = false;
$mail->Host = 'email_smtp_host'
$mail->SMTPAuth = false
$mail->Username = 'username'
$mail->Password = 'password'
$mail->SMTPSecure 'tls'
$mail->Port = '587'
If you're using VPS and with httpd service, please check if your httpd_can_sendmail is on.
getsebool -a | grep mail
to set on
setsebool -P httpd_can_sendmail on
Try adding this line to your script. This worked for me!
$mail->Mailer = “smtp”;
This is usually a result of the server not accepting SSLv2 or SSLv3 connections which is a standard for cPanel/WHM in favor of TLS only connections. You can check this by going to WHM>>Service Configuration>>Exim Configuration Manager -> Options for OpenSSL
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once "PHPMailer/src/Exception.php";
require_once "PHPMailer/src/PHPMailer.php";
require_once "PHPMailer/src/SMTP.php";
$mail = new PHPMailer();
$mail ->isSMTP();
$mail ->Host ="smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail ->Username = 'youremail#gmail.com';
$mail ->Password = 'password';
//$mail ->SMTPSecure=PHPMailer::ENCRYPTION_STARTTLS;
$mail ->Port = '587';
$mail ->SMTPSecure ='tls';
$mail ->isHTML(true);
$mail ->setFrom('youremail#gmail.com','email send name');
$mail ->addAddress('receiver#gmail.com');
$mail ->Subject = 'HelloWorld';
$mail ->Body = 'a test email';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if ($mail->send()){
echo "Message has been sent successfully";
}else{
echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
make sure that you configure less secure app settings in gmail using this link https://www.google.com/settings/security/lesssecureapps and make sure you downloaded PHPMailer-master.zip from github
working fine with MAMP server locally :)
After days of searching, I found out that the protocol name needs to be in lowercase.
$mail->SMTPSecure = "ssl"; # lowercase
find the "class.smtp.php" file
original:
$this->smtp_conn =fsockopen(
$host,
$port,
$errno,
$errstr,
$timeout
);
change to:
$this->smtp_conn = #stream_socket_client(
$host,
$port,
$errno,
$errstr,
$timeout
);
My mail send code:
$mail = new PHPMailer(true);
$mail->IsSMTP();
try {
$mail->Host = 192.168.205.19;
$mail->Port = 25;
$mail->SMTPDebug = 2;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "mymailadress#mysite.com";
$mail->Password = "mypassword";
$mail->From = "mymailaddress#mysite.com";
$mail->FromName = "My Mail Address";
$mail->SetFrom("mymailaddress#mysite.cm", "My Mail Address");
$mail->AddAddress('toaddress#mysite.com');
$mail->Subject = "Test for subject";
$mail->MsgHTML("Test my mail body");
if ($mail->Send()) {
$result = 1;
} else {
$result = "Error: " . $mail->ErrorInfo;
}
} catch (phpmailerException $e) {
$result = $e->errorMessage();
} catch (Exception $e) {
$result = $e->getMessage();
}
return $result;
Result?
SMTP -> FROM SERVER:220 evo.callpex.int Microsoft ESMTP MAIL Service ready at Tue, 27 Nov 2012 17:45:24 +0200
SMTP -> ERROR: Password not accepted from server: 535 5.7.3 Authentication unsuccessful
I'm using PHPMailer class for sent mail. And SMTP. I'm connecting to Exchange Mail server. But I have this error.
Why?
Thanks!
May be you are using Administrator credentials. Don't know why but even I was not able to send mail using PHPMailer with admin credentials(There may be some security measures applicable for Administrator details). Try giving any other user credentials, it will work.
It works for me with other user credentials.
And, In your code
$mail->From = "mymailaddress#mysite.com";
$mail->FromName = "My Mail Address";
$mail->SetFrom("mymailaddress#mysite.cm", "My Mail Address");
$mail->SetFrom("mailid","name") itself will set From & FromName values. You no need to set that again.
I think your variable $mail->Host should be a string like $mail->Host = '192.168.205.19'; and not without quotes.
I don’t know if this is sorted or not, but exchange servers typically don’t support SMTP. I believe it is possible to enable SMTP or create an SMTP connector though.