php mail script not working using phpMailer - php

I am using phpMailer to send emails using PHP.
The mail is being sent but it is not received in inbox/spam or anything.
It is surprising that it was working until few days ago.
I have tested it and almost 500-600 emails were sent and received.
But suddenly it stopped "working".
Here's my Php script:
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->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 = "abcd";
// $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 Team,<br>I would like to request leave for the leave dates specified as follows.
Application Date:' . $f3->get('issuedDate') . '<br>Leave requested from:' . $f3->get('leaveFrom') . '<br>Leave requested to:' . $f3->get('leaveTo') . '<br>Leave Description:' . $f3->get('leaveDescription') . 'Leave Type:' . $f3->get('leaveType').'<br><br>Hoping for a positive response.<br><br> Thank you.';
}
$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 received a junk email though [only one] that says :
This sender failed our fraud detection checks and may not be who they appear to be. Learn about spoofing
I cannot figure out what's going wrong.
It is working until previously. And I have tons of emails in my inbox.
Could it be that there's some limit of sending emails?? Or could it be that some one reported it as spam or spoofing??
Any help is very much appreciated. Thanks.

Because you're using SMTPSecure = 'ssl' you won't get any debug output with SMTPDebug = 2 because that only shows SMTP-level output; You need SMTPDebug = 3 to show connection-level problems. This is probably caused by out of date CA certificates in your PHP config. There have been lots of reports of this because gmail changed theirs recently (why your script stopped working). It's covered in the troubleshooting guide.
Also, why are you putting HTML tags in your plan-text AltBody? They won't work in there.

Related

sending multiple emails issue phpMailer

I'm trying to send multiple emails (more than 100) to existing as well as non-existing recipients, since that is what my requirement is.
I'm using phpMailer that uses Gmail SMTP server.
Recipients are stored in array, and looped through this array to add as recipients.
public static function mailTo($recipients)
{
$f3 = \Base::instance();
$user = AclHelper::getCurrentUser();
$template= new \Template;
$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("abhshrestha#growbydata.com");
$mail->addAddress("rmali#growbydata.com");
foreach($recipients as $recipient){
$mail->addAddress($recipient);
}
$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 = "growbydata.np#gmail.com";
$mail->Password = "abcd";
$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;
$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;
}
}
Recipients are both existing addresses as well as non-existing eg. abc#gbd.gbdtest.
When I send emails to all these recipients (130+) from Gmail directly, existing addresses receive them.
But when I send emails to the same recipients using phpMailer, existing addresses also don't get emails.
Could this be because using phpMailer, emails can be only sent to 100 recipients at a time??
What could be the issue with phpMailer on this??

SMTP connect() failed phpMailer [out-of-date CA certificate issue]?

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...

PHPMailer - Could not authenticate

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.

invalid puny Encode while trying to send email using stmp configuration

i'm trying to send a mail using stmp configuration but it always displays a puny encode invalid error . I'm guessing it's my validation method that has a bug when the prce8 is selected ( i'm using php5 so it selects as best choice pcre8). I have already checked on that answer but still does not work !
<?php
require_once('class.mail.php');
$to=isset($_POST['verify'])?$_POST['verify']:false;
$subject="TSHED Email verification";
$message='<html><p> my message </p></html>';
$mail = new PHPMailer();
$mail->isSMTP(); // telling the class to use SMTP
// SMTP Configuration
$mail->SMTPsecure='ssl';
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.gmail.com "; // SMTP server
$mail->Username = "myEmail";
$mail->Password = "mypassword";
$mail->Port = 465; // optional if you don't want to use the default
$mail->From = "<FromanEmail>";
$mail->FromName = "Name";
$mail->Subject = $subject;
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->isHTML($message);
$mail->Body=$message;
$mail->msgHTML($message);
// Add as many as you want
$mail->AddAddress($to,'USER');
if(!$mail->Send())
{ //echo"endterer";
$response = "Message error!".$mail->ErrorInfo;
echo $response;
echo $to;
}
else {
$response = "Message sent!";
echo $response;
}
?>
Any Help Please ?
my pcre8:
case 'pcre8':
return (boolean)preg_match(
'/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}#)' .
'((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
'(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
'([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
'(?2)")(?>(?1)\.(?1)(?4))*(?1)#(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
'(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
'|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
'|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
'|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
$address
);
exemple of valid Email: ouedson0128#yahoo.fr
Error :Invalid address: (punyEncode)
Seems it is a bug in phpMailer. Try another version

PHP Mailer - Internal Server Error

I have been trying to make the contact form on my website to work and I've spent weeks trying to figure it out and I couldn't.
Here's the problem - I purchased a web template and it came with the PHPMailer. I'm now done plugging my content into the template, but the contact form has been a pain. I've followed the instructions the best I know on the PHP file, but it's giving me an "Internal Server Error" when I am testing the contact form.
Here's the code that came with my purchase:
$name = trim($_POST['name']);
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$site_owners_email = 'name#mydomain.com'; // Replace this with your own email address
$site_owners_name = 'My Name'; // Replace with your name
try {
require_once('/Beta-BRC/php/PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "[WEB Form] ".$subject;
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com"; // Replace with your SMTP server address
$mail->Port = 465;
$mail->SMTPSecure = "SSL";
$mail->SMTPAuth = true; // Turn on SMTP authentication
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
//echo "true";
if($mail->Send()) {
echo "true";
} else {
echo "Error sending: " . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo $e;
}
Quick note - I've alrealy tried using a GMAIL account on this part but it still does not work.
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
There's no need to log into Gmail with phpmailer. Below is an example of my phpmailer function using the default settings.
public function sendEmail($toaddress,$toname,$subject,$message){
if($template = file_get_contents('/home/username/domains/mydomain.com/public_html/html/email-template.html')){
$template = str_replace("[SUBJECT]",$subject,$template);
$template = str_replace("[CONTENT]",nl2br($message),$template);
$mailer = new PHPMailer;
$mailer->XMailer = "Organization Name 4.0.0";
if($this->is_logged_in()){
$mailer->AddCustomHeader("X-Originating-User-ID",$this->acct['id']);
}
$mailer->AddCustomHeader("X-Originating-IP",$_SERVER['REMOTE_ADDR']);
$mailer->setFrom("outbound#mydomain.com","From Name");
$mailer->AddAddress($toaddress,$toname);
$mailer->Subject = $subject;
$mailer->MsgHTML($template);
$mailer->AltBody = $message;
return $mailer->Send();
}else{
return false;
}
}
The email address listed doesn't actually exist. The email is just being sent from my server and phpmailer just says it's from that email address.
Try modifying my function to suit your needs and let me know how that works.
Note: You'll need to make sure your mail server is turned on for this to work
Although you don't have to use my function at all. Try debugging your code by checking some error logs on your server. Typically in the apache error logs (if you're running apache, however). Checking error logs is a huge part of troubleshooting your code and often can help you become more proactive.
I hope this helps even the slightest!
The specific cause of the Internal Server Error is the incorrect path you've supplied to the require_once statement that loads the PHPMailer class.
The path you've supplied is /Beta-BRC/php/PHPMailer/class.phpmailer.php, where the correct statement should be
require_once('/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
or perhaps more generally:
require_once($_SERVER['DOCUMENT_ROOT'].'/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
You've provided effectively a URL, but PHP requires the path in the server file system, which is not the same.
That should get you past this error. It's possible that there are others.

Categories