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
Related
I've been using phpMailer to send emails until few days ago, and it stopped working surprisingly.
I'm using GMAIL SMTP server as a host.
Here's what the Exception and debugging message shows in console :
2017-12-19 05:39:02 Connection: opening to ssl://smtp.gmail.com:465, t=10, opt=array (
)
2017-12-19 05:39:02 SMTP ERROR: Failed to connect to server: (0)
2017-12-19 05:39:02 SMTP connect() failed.
And here's my mail functionality:
public static function mailTo($recipients)
{
$f3 = \Base::instance();
$edit = $f3->get('editTrue');
$user = AclHelper::getCurrentUser();
$template= new \Template;
if(isset($edit))
{
$mailBody = $template->render('leave/requestEdit.html');
}
else
{
$mailBody= $template->render('leave/emailTemp.html');
}
// When true, PHPMailer returns exceptions
$mail = new PHPMailer(true);
try {
$mail->isSMTP(); // Set mailer to use SMTP
$mail->isHTML(true);
$mail->addAddress($user['email']);
$mail->addAddress("malakar.rakesh1993#gmail.com");
// foreach($recipients as $recipient){
// $mail->addCC($recipient);
// }
$mail->SMTPDebug = 4;
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->Username = "malakar.rakesh1993#gmail.com";
$mail->Password = "abc123";
// $mail->Host = $f3->get('GBD.smtp.host'); // Specify main and backup SMTP servers
$mail->setFrom($user['email']);
$userFullName = trim(ucfirst($user['firstname'])) . " " . trim(ucfirst($user['lastname']));
$mail->FromName = $userFullName;
$mail->Body = $f3->get('message');
$mail->Body .="<br>". $mailBody;
if(isset($edit))
{
$mail->AltBody = '';
}
else
{
$mail->AltBody = 'Hello.. Not working';
}
$mail->Subject = 'Updates on leave date applied';
$mailStatus = (boolean)$mail->send();
if ($mailStatus === true)
{
return $mail;
}
}
catch (phpmailerException $e)
{
$response = array(
'status'=>'error',
'message'=>'Got some error while sending emails',
'exceptions'=>$e->getMessage()
);
return $response;
}
catch (Exception $e) {
$response = array(
'status'=>'error',
'message'=>'Got some error while sending emails',
'exceptions'=>$e->getMessage()
);
return $response;
}
}
I also tried using tls as encryption protocol and 587 port, but gives 500 internal server error.
The same code is running in development version in server, but unfortunately not in my localhost.
I was suggested of out-dated CA certificate in my system, and I tried renewing the up-to-date CA certificate following the link Trobuleshooting, but it's not working either.
Stupid maybe but I tried pinging to smtp.gmail.com [without ssl and port] in my command prompt and I'm receiving feedback.
Could it be that Google limits email sending? But I can still access my account.
I have followed almost every articles and solutions available in the Internet.
Please help me through this...this is driving me crazy.
Any help is very much appreciated. Thanks...
I've written the following code to send email using PHPMailer. But what i'm trying to get working is first attempt a send via SMTP TLS and if that fails then send the mail without SMTP. But the code seems to fail because it doesn't like to run the PHPMailer function twice. If I run the function once either calling it to send via SMTP or not both work. But it doesn't work if SMTP fails.
function processEmail($to, $message, $skip_smtp){
date_default_timezone_set('Europe/London');
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
if (!isset($skip_smtp) || empty($skip_smtp)){
$mail->isSMTP();
}
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.domain.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "my_smtp_username";
$mail->Password = "my_smtp_password";
$mail->setFrom('from#myemail.com', 'From Name');
$mail->addAddress($to, $to);
$mail->msgHTML($message);
if (!$mail->send()) {
return false;
} else {
return 1;
}
}
$smtp_result = processEmail($to, $message);
if ($smtp_result>=1){
echo "Sent using secure TLS SMTP";
} else {
processEmail($to, $message, 1);
echo "SMTP Failed - Attempted to send without SMTP ";
}
Looking at your existing code, I've gathered that your relaying mail over another SMTP server so unsure why your testing if TLS is available. Does your relaying server sometimes fail on TLS? The below solution would be best suited using OOP as this function is a bit excessive. I've heavily commented so my logic should be pretty straight forward. Some of the key points is that the function is Recursive meaning it will call it self if TLS fails keeping the code running inside one function. Secondly, re-using PHP Mailer with the same execution will have issues so I have unset() the initial $mail object on second call as well as setting the include to require_once. As noted, you will need to check with your SMTP provider on the TLS port used and SMTP port (if any) to ensure it works. I've tested with my provider and this works with no issues.
function sendEmail($to, $message, $skip_smtp=1) {
date_default_timezone_set('Europe/London');
require_once 'PHPMailer/PHPMailerAutoload.php';
//You will need to check your provider for these settings
if ($skip_smtp === 0) {
$port = 25; //Usual port for non TLS/SSL
} else {
$port = 465; //Port for relay server - likely to be 25, 465 or 587
$mail->SMTPSecure = 'tls'; //Send via TLS Encryption - SSL or TLS (Dependent on Relay Server)
}
$mail = new PHPMailer();
$mail->SMTPDebug = 3; //Enabled this so you can see what's happening - Dont forget to set to 0 in production
$mail->Debugoutput = 'html';
//SMTP Relay Server Settings
$mail->isSMTP(); //Send as SMTP - Should always be set unless you would like to use another method like sendmail()
$mail->Host = 'smtp.relay.com';
$mail->Port = $port;
$mail->Timeout = 5; //Set your Timeout in Seconds - Default is 5mins which is abit excessive when testing
$mail->SMTPAuth = true; //Relay Server Auth Details
$mail->Username = "SMTP RELAY USERNAME";
$mail->Password = "SMTP RELAY PASSWORD";
//Email Details
$mail->setFrom('test#test.com');
$mail->addAddress($to);
$mail->Subject = 'My Subject';
//Email Content
$mail->isHTML(true); //Set HTML
$mail->Body = $message; //HTML Body
$mail->AltBody = $message; //Failover for Non-HTML
switch ($mail->send()) {
case false:
if ($skip_smtp === 0) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Error Sending TLS...trying Non TLS';
unset($mail); //Unset Object
sendEmail($to, $message, $skip_smtp=0); //Recursive function -> passing 0 to skip TLS
}
break;
case true :
echo 'Message has been sent';
break;
default :
echo 'Error';
}
}
//Your Function
sendEmail('test#test.com', 'Test Body');
?>
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've been looking for answer more than a week. Im stuck with this problem. I have downloaded sendmail folder and configure it. Yes it says true message sent but actually it doesnt went to the mail. So I decided to put PHPmailer as I have read at some websites. i downloaded PHPmailer and configure it also. and when I am running it there is an error. Fatal error: Class 'SMTP' not found in C:\wamp\www\Project\PHPMailer\class.phpmailer.php on line 1197.
And I have also read some solution that paste the code before the line 104 #connectto the smtp server. but my line 104 looks like this.
public $CRLF = "\r\n";
/**
* Debug output level.
* Options:
* * self::DEBUG_OFF (`0`) No debug output, default
* * self::DEBUG_CLIENT (`1`) Client commands
* * self::DEBUG_SERVER (`2`) Client commands and server responses
* * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
* * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages
* #type integer
*/
public $do_debug = self::DEBUG_OFF;
Can you help me guys. Im stuck here.
Have you got the newest PHPMailer with the autoloader?
See https://github.com/PHPMailer/PHPMailer as the mailer no longer calls the SMTP class from within the PHPMailer class. This was a pain when I updated as calling the mailer directly produced this error.
Also turn on PHPMailers debugging feedback and see what it says.
Here is a sendMail() method that I use in a lot of projects. It uses PHPMailer.
function sendMail($toAddress, $subject, $body, $AttachmentFilePath) {
$mail = new PHPMailer();
$mail->IsSMTP ();
$mail->CharSet = 'UTF-8';
// nable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0; // To prevent any outpur
// Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
// Get the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// Get the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
// Get the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
// Whether to use SMTP authentication
$mail->SMTPAuth = TRUE;
// Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "your.email#gmail.com";
// Password to use for SMTP authentication. Specific to the Lead Qualifier Tool
$mail->Password = "YourPassWordHere";
// Set who the message is to be sent from
$mail->SetFrom ( 'your.email#gmail.com', 'Your Name' );
// To Address
$mail->AddAddress ( $toAddress, $toAddress );
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = $body;
// Add attachment
if ($AttachmentFilePath != NULL)
$mail->AddAttachment ( $AttachmentFilePath );
if (! $mail->Send ()) {
echo "<br />Error while sending e-mail: " . $mail->ErrorInfo;
} else {
// echo "Message sent!";
}
}
Hope it helps! :-)
Also, since you are using GMail, make sure you create an ASP(Application Specific Password), and use it here, and not your real password.
I got a project which I need to create a personal web site but I can not send e mail via contact form. Could you pls assist me what do I need to do in order to fix it.
I have added class.phpmailer.php and class.smtp.php. Here is php code;
<? php
include 'class.phpmailer.php';
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "behzatdeniz82#gmail.com";
$mail->Password = "myseccretpassword"; //Don't reveal password with others
$mail->SetFrom("behzatdeniz82#gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("behzatdeniz99#gmail.com");
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
After I change the php code as above, now I begin to receive this error. Can anyone help me how to fix ?
SMTP -> ERROR: Failed to connect to server: Unable to find the socket transport "ssl"
- did you forget to enable it when you configured PHP? (1702478359)
SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error:
Could not connect to SMTP host.
It seems like SetFrom method is missing. There are multiple versions of PHPMailer available. Download PHPMailer 5.1 which contains a setFrom method:
public function SetFrom($address, $name = '',$auto=1) {
Just Try.
just a small bug, which may be the solution: a missing ' here, after My Name, $mail->SetFrom($mail->Username, 'My Name);