Unable to send email using PHPMailer and CRON job - php

I am experiencing an issue automating the sending of emails using PHPMailer and a cron job. I am using a shared hosting server and CPanel. I have tested my PHPmailer installation and have been able to successfully send a basic email by running the below script in the browser.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
/* Exception class. */
require '/home/eepherg/public_html/mobiq1.2/lib/PHPMailer-master/src/Exception.php';
/* The main PHPMailer class. */
require '/home/eepherg/public_html/mobiq1.2/lib/PHPMailer-master/src/PHPMailer.php';
/* SMTP class, needed if you want to use SMTP. */
require '/home/eepherg/public_html/mobiq1.2/lib/PHPMailer-master/src/SMTP.php';
/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new PHPMailer(TRUE);
/* Set the mail sender. */
$mail->setFrom('darth#empire.com', 'Darth Vader');
/* Add a recipient. */
$mail->addAddress('test#provision.com', 'Emperor');
/* Set the subject. */
$mail->Subject = 'Force';
/* Set the mail message body. */
$mail->Body = 'There is a great disturbance in the Force.';
/* Finally send the mail. */
$mail->send();
?>
I have setup a CRON job as per the below to run once a day ...
12 00 * * * /usr/local/bin/php /home/eepherg/public_html/mobiq1.2/test.php
This CRON job runs without any errors, however no email is received. Is there perhaps an issue with my references or does anyone have any ideas why the script will work when run in the browser but not when run using the CRON job?

The reason you can't see whats going wrong is because you have no error handling at all. Look at the examples provided with PHPMailer to see how to detect and report send errors - this will give you some idea of what's going on:
if (!$mail->send()) {
echo 'Mailer Error: '. $mail->ErrorInfo;
} else {
echo 'Message sent!';
}
You can also try enabling debug output:
$mail->SMTPDebug = 3;
Because this all happens during a cron run, it may not be obvious where the output goes, but you can configure cron to email any output (normal error-free scripts should produce no output) to you. To do that, just put your email address in an environment variable inside your cron file:
MAILTO=me#example.com
With that set, you should receive any output that cron generates.

Related

How Use Sendinblue with PHPMailer

I'm setting up an email configuration with PHPMailer and just work fine with local email in my office, but since I want use Sendinblue as an email API I just stucked and it didn't work.
I tried to find some suggest to fixed it but stucked. Did anyone try to figure out what I'm looking for about Sendinblue with PHPMailer?
With PHPMailer Library in background, I usually use this code to run my program
function send_mail2($from,$from_name,$to,$to_name,$cc,$cc_name,$cc2,$cc_name2,$cc3,$cc_name3,$subjek,$template,$is_smtp,$usermail,$password){
$sendmail = new PHPMailer();
if($is_smtp = 'Y'){
$sendmail->IsSMTP(); // enable SMTP
// $sendmail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$sendmail->SMTPAuth = true; // authentication enabled
$sendmail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$sendmail->Host = "192.x.x.x";
$sendmail->Port = 465; // or 587
$sendmail->Username = "xxx#xxx.com";
$sendmail->Password = "xxx";
}
$sendmail->setFrom("xxx#xxx.com","xxx#xxx.com"); //email pengirim
$sendmail->addReplyTo("xxx#xxx.com","xxx#xxx.com"); //email replay
$sendmail->addAddress($to,$to_name);
$sendmail->AddCC($cc,$cc_name);
$sendmail->AddCC($cc2,$cc_name2);
$sendmail->AddCC($cc3,$cc_name3);
$sendmail->Subject = $subjek;
$sendmail->Body=$template;
$sendmail->isHTML(true);
if(!$sendmail->Send()) {
return "failed";
}else{
return "success";
}
}
I just want to find how to use Sendinblue with PHPMailer.
First of all, it looks like you're using an old version of PHPMailer and have based your code on a very old example, so upgrade.
It doesn't look like you're even trying to use sendinblue; you're pointing your script at a local mail server. Because you're using a literal IP address, SSL will never work because it will fail to verify the certificate.
If you want to use sendinblue directly from PHPMailer, you need to use sendinblue's SMTP servers, and that will be covered in their documentation. If they don't provide an SMTP service (like say mailgun does), you will need to use their HTTP API instead (which has plenty of documentation). You can't use PHPMailer for talking to that, though you can use it for generating messages to send, for example by doing everything as you currently are except don't call send(); do this instead:
$message = $sendmail->getSentMIMEMEssage();
This will give you a fully-formatted RFC822 message ready to submit to an HTTP API.
When you need to configure sendinblue with PHPMailer,
At that time, first, get all configuration detail from your sendinblue account
like Host, Username, Password
And then your PHPMailer use getSentMIMEMEssage(); instend of $mail->isSMTP() or $mail->isMail()
Please check the below screenshot for reference.

Returning the error why mail failed to send within Yii 2's base mailer class

I'm using Yii 2 and am using the mailer from the base mailer class and for the most part it is working fine, but sometimes it fails to send..... so my code is like:
// Let's start composing the message
$mail = Yii::$app->mailer->compose($view_data, $view_params);
//.........
// Send the message
$send = $mail->send();
Sometimes $send is false but I'm not sure how you find out WHY it is false? Is there a way to get the error that made it become false?
If you are sending multiple recipients message, you should check for failures : http://swiftmailer.org/docs/sending.html#getting-failures-by-reference, e.g. :
if (Yii::$app->mailer->getSwiftMailer()->send($message->getSwiftMessage(), $failures))
{
// do what you want with $failures var
}
And if you really want to handle smtp errors in your yii app, you should use swiftmailer logger plugin : http://swiftmailer.org/docs/plugins.html#logger-plugin
PS : first I would check yii and smtp logs to see what kind of errors occurs...

E-mail not getting sent in Joomla in combo with VM

I'm new to SO, so bear with me please. I'm fairly noobish regarding code, I'm mostly a webdesigner, not developer. But my own webdeveloper is having a hard time with this problem so I'm trying to find some help where ever I can get.
So, we got this problem on a Virtuemart shop, running version 2.5.23 of Joomla with VM 2.6.10.
Server info:
PHP Built On Linux web04 3.13.0-35-generic #62~precise1-Ubuntu
Database Version: 5.1.73-0ubuntu0.10.04.1-log
Database Collation: utf8_general_ci
PHP Version: 5.3.10-1ubuntu3.14
Web Server: Apache
WebServer to PHP Interface: apache2handler
Joomla! Version: Joomla! 2.5.23 Stable [ Ember ] 24-July-2014 14:00 GMT
So this is not sending mail anywhere. We got it on a testserver and over there, life is good. It's sending e-mail. The testserver is running PHP 5.24.
I've used this to see if this checks out:
<?php
$to = "dontsentmemail#gmail.com";
if( mail( $to , 'This is a test message.' , 'Is this working?' ) ) {
echo 'Email sent.';
} else {
echo 'Email failed to send.';
}
?>
This is working fine. And I'm about to pull out all my hair. We've tried SMTP mail handling, and again, working like a charm on the testserver but it won't work on the live site.
does anybody know if is VM/joomla is using mail() directly or maybe using JUtility::sendMail() as default, and if we can change that, to make it work? Anyone got any ideas?
EDIT
I wasn't aware Joomla already includes its own version of PHPMailer. See Lodder's answer for a better out-of-the-box solution!
Try switching to a specialist mail library, e.g. PHPMailer to send the mail, instead of php's mail function.
I too had a similar problem, emails sent but not delivered, and no bounce messages. PHPMailer managed to send email that also got delivered.
<?php
require_once('path/to/PHPMailerAutoload.php');
//Create a new PHPMailer instance
$mail = new PHPMailer();
// Set PHPMailer to use the sendmail transport
$mail->isSendmail();
// Set who the message is to be sent from
// Name is optional
$mail->setFrom('somebody#yourdomain.com', 'Joe Bloggs');
//Set who the message is to be sent to
// Name is optional
$mail->addAddress('dontsentmemail#gmail.com', 'Jane Bliggs');
//Set the subject line
$mail->Subject = 'Is this working?';
// Set plain text body
$mail->IsHTML(false);
$mail->Body = 'This is a test message.';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
I would personally use Joomla's built-in JMail class which uses PHPMailer. Have a look at the following:
$mailer = JFactory::getMailer();
$mailer->setSender('dontsentmemail#gmail.com');
$mailer->addRecipient('from#emailaddress.com');
$mailer->setSubject('Your subject');
$body = "Some email text";
$mailer->setBody($body);
$send = $mailer->Send();
if ( $send !== true )
{
echo 'Error sending email';
}
else
{
echo 'Mail sent';
}
You may want to change from#emailaddress.com to whatever suits your needs. There are also some additional features for this class which can be found on the Joomla documentation:
http://docs.joomla.org/Sending_email_from_extensions
Update:
I wasn't aware that you were using a separate PHP file. At the top of your PHP file, you will need to import the Joomla framework like so:
define( '_JEXEC', 1 );
define('JPATH_BASE', __DIR__);
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
$app = JFactory::getApplication('site');
You may need to change the value for JPATH_BASE so that your script points to the root of your Joomla site, relative to where you PHP file is located.
Hope this helps

Sent mails with phpmailer don't go to "Sent" IMAP folder

in my CRM online system I control ingoing mails with IMAP protocol.
Now I'm making sending mails with phpmailer and SMTP protocol.
Everything is ok but I have one wierd thing. How to make sent with phpmailer script mails go to "Sent" IMAP folder?
There is now a method getSentMIMEMessage in PHPMailer which returns the whole MIME string
$mail = new PHPMailer();
//code to handle phpmailer
$result = $mail->Send();
if ($result) {
$mail_string = $mail->getSentMIMEMessage();
imap_append($ImapStream, $folder, $mail_string, "\\Seen");
}
I found easier way to do this.
PHPmailer prepares email as string - all You have to do is to put it into right IMAP folder.
I expanded phpmailer class with this code (since vars are protected I can't reach them):
class PHPMailer_mine extends PHPMailer {
public function get_mail_string() {
return $this->MIMEHeader.$this->MIMEBody;
}}
PHP code:
$mail= new PHPMailer_mine();
//code to handle phpmailer
$result=$mail->Send();
if ($result) {
$mail_string=$mail->get_mail_string();
imap_append($ImapStream, $folder, $mail_string, "\\Seen");
}
It works well.
Well, it's pretty difficult, but can be done.
Take a look at the imap-append function.
By being connected to an IMAP stream resource, you can use the imap-append() to append your mails to the Sent folder of your IMAP account.
But reading through the comments will show you that it's a bit tedious to accomplish, but certainly not impossible - you'll probably need to code something on your own, since phpmailer doesn't support this out of the box (and will most likely be too time consuming to implement instead of making something yourself).
You need to be relaying your sent mail through the IMAP host
The IMAP host needs to support the feature (which very few do)
If either of these two points are not true, the short answer is "You can't". In short, really it's down to the mail provider, not your code.
As much as I hate M$, Exchange is one place where they really have got things right - if you are using an Exchange server, all of this is handled for you.
This works well :
Php Manual
if (!$mail->send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
} else{
//echo "Message sent!";
//Section 2: IMAP
//Uncomment these to save your message in the 'Sent Mail' folder.
if (save_mail($mail)) {
echo "Message saved!";
}
}
//function
function save_mail($mail)
{
$providerMail = 'Gmail';
$providerMailSentFolder = 'Sent Mail';//You can change 'Sent Mail' to any folder
$providerMailImap = 'imap.gmail.com';//imap.one.com
$path = "{".$providerMailImap.":993/imap/ssl}[".$providerMail."]/".$providerMailSentFolder;
//Tell your server to open an IMAP connection
//using the same username and password as you used for SMTP
$imapStream = imap_open($path, $mail->Username, $mail->Password);
$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
imap_close($imapStream);
}

Two emails when sent via SMTP

I've used two PHP email scripts and routing it through my SMTP server, when I do this though it sends two of the same email.
When I use mail() this doesn't happen, but I'd much rather use SMTP.
Any ideas why this may be occuring?
If you're setting the 'To' and/or 'Recipient' header multiple times, the SMTP server could interpret that as separate e-mail address, thus you'll receive the multiple e-mails.
I'd recommend using the PEAR Mail class. Very simple to use, and handles much of the work for you. It supports multiple backends including SMTP. Likewise, if you want to expand your class to send HTML emails, the Mail_Mime class handles this very nicely, providing methods to set the plain-text body and the HTML body (in case the recipient doesn't support HTML).
So if you're only using PHPMailer without editing it's code, it's not your script's fault. Maybe check your SMTP server's configuration?
function send_email($from, $fromname, $to, $subject, $body, $alt = '')
{
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$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 = 'localhost'; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
//$mail->AddReplyTo($from, $fromname);
$mail->AddAddress($to);
$mail->SetFrom($from, $fromname);
$mail->Subject = $subject;
//$mail->AltBody = $alt; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
$mail->Send();
echo 'Message Sent OK';
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //Pretty error messages from PHPMailer
}
catch (Exception $e)
{
echo $e->getMessage(); //Boring error messages from anything else!
}
}
That's the current function so far
Based on your code, if it's the class which is at fault, you'd expect to get 'Message Sent OK' twice (I can't see why that would happen though). If you don't, then I'd be looking at your SMTP server (maybe via a call to support).
I'm assuming you've disabled Reply-to to rule it out as a cause in this case? Note: I'm not suggesting that would affect anything (other than you likely being classified as spam).
Incidentally, I moved from PHPMailer to Swift Mailer some time ago & have never looked back. If you don't get any joy from support then I'd try at least testing with Swift Mailer.
I agree with what da5id said, why dont you take the second error message out. Further have you checked the receiver whether they REALLY get 2 messages?

Categories