How to know CakePHP mail has been sent successfully or not? - email

In my CakePHP web application I'm sending mails and if mail is successfully sent then updating data base field 'mailSent' to true.
But How to know that mail is successfully sent or not?

You can use a try catch block to check whether the mail was successfully send or not, you can not detect or check if the mail was successfully delivered to the recipient. That is a different scenario.
try {
if ( $this->Email->send() ) {
// Success
} else {
// Failure, without any exceptions
}
} catch ( Exception $e ) {
// Failure, with exception
}
above is just sudo code you can change variable as you need.
let me know if i can help you more.

Related

Getting repeated calls on facebook-messenger webhook

I have successfully setup a facebook-messenger webhook. Until yesterday I was able to send and receive messages as well. But today, when I am sending one message from user, I am getting multiple calls at server webhook POST API. They never seem to stop.
Do all of those calls have the same content or are they different? You could log the exact message string that facebook sends to you and see what they include.
For example there's a message delivery callback that informs you that the user received the message. The JSON looks like this:
{'delivery': {'mids': ['mid.146174459xxx:30a42600a95exxxxx'], 'seq': 429, 'watermark': 146174459xxx}, 'recipient': {'id': xxxxxxxx}, 'sender': {'id': xxxxxx}}
Edit: It could also be the case that your are not confirming incoming calls with a http status 200. If facebook receives an error from your webhook the message will be sent multiple times.
Figured it out. I was sending response to every communication that came from facebook. So I ended up responding to ACK messages as well. In turn one more ACK came. Thats why it led to infinite loop.
In this page we can find different object structures for messages recieved:
text
{
"object":"page",
"entry":[
{
"id":PAGE_ID,
"time":1457764198246,
"messaging":[
{
"sender":{
"id":USER_ID
},
"recipient":{
"id":PAGE_ID
},
"timestamp":1457764197627,
"message":{
"mid":"mid.1457764197618:41d102a3e1ae206a38",
"seq":73,
"text":"hello, world!"
}
}
]
}
]
}
Message-Delivered callback
{
"object":"page",
"entry":[
{
"id":PAGE_ID,
"time":1458668856451,
"messaging":[
{
"sender":{
"id":USER_ID
},
"recipient":{
"id":PAGE_ID
},
"delivery":{
"mids":[
"mid.1458668856218:ed81099e15d3f4f233"
],
"watermark":1458668856253,
"seq":37
}
}
]
}
]
}
So, for differentiating we can refer to entry[0].messaging[0].message this exist only in user sent message. Callback or postbacks do not contain this part.
Check for this, before responding. If it exists, respond, otherwise dont.
My problem was similar but I was getting Multiple Message delivery posts. After a few hours of frustration, I realized that Message Delivered callback is called every time the message is delivered to EVERY DEVICE. So, if you are logged into both web and mobile app, the callback would be called twice.
When working with messenger of facebook you need to take in account two things after you send the message :
A) Message Delivery
B) Message Read
Since you are working with webhooks this will be trigger everytime one of the events happen (receive a message , deliver the message you sent , the user read the message). So if you activate for example message_deliveries in your webhook and you send a message as action , you will end up in a loop.
The proper way to handle this is in the base code. PHP example :
// Skipping delivery messages
if (!empty($message['delivery'])) {
#Do something here if you want
continue;
}
// Skipping read messages
if (!empty($message['read'])) {
#Do something here if you want
continue;
}
Hope it helps !

How to monitor delivery of emails sent by salesforce by source code?

I have following questions. Assuming I have following code
public class MessageMaker {
public static void helloMessage() {
System.debug( 'Entry point' );
Case c = new Case();
insert c;
EmailMessage e = new EmailMessage();
System.debug( 'EmailMessage created' );
e.parentid = c.id;
// Set to draft status.
// This status is required
// for sendEmailMessage().
e.Status = '5';
e.TextBody =
'Sample email message.';
e.Subject = 'Apex sample';
e.ToAddress = 'my#mail.com';
insert e;
List<Messaging.SendEmailResult>
results =
Messaging.sendEmailMessage(new ID[]
{ e.id });
System.debug(results.size());
System.debug(results[0].success);
System.debug(results[0].getErrors().size());
System.assertEquals(1, results.size());
System.assertEquals(true, results[0].success);
}
}
1.First question. I want to find out using apex code if the message was really delivered.
Here documentation says http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_sendemail_emailresult.htm
Even if success = true, it does not mean the intended recipients received the email, as it could have bounced or been blocked by a spam blocker. Also, even if the email is successfully accepted for delivery by the message transfer agent, there can still be errors in the error array related to individual addresses within the email.
So I have been trying to send email by apex code and look for results[0].success. It seems it says like it is described in documentation, so success is true even though email address was incorrect.
Also I have tried to check this manually through email logs http://eu2.salesforce.com/help/doc/en/email_logs.htm
And I have found following row in resulting log regarding my email sent to incorrect address
9/2/2013 9:36 66/FC-09306-20B54225 T julfy#i.ia
julfy=i.ua__0-6uvic1ltvun1nf#95mngihd2hpe0w.b-ysubea0.bl.bnc.salesforce.com 1434 005b0000000J7bm
<_0vTJ000000000000000000000000000000000000000000000MSHRSY00W1-CKg3DShWC5xu24ccHFA#sfdc.net>
1 311.627583 421 4.4.0 [internal] no MXs for this domain could be
reached at this time
But I don't know how to access this information by apex code. Any thoughts?
Second question. If message was delivered and recipient forwarded it, is any possibility to monitor that using apex code? Anybody?
You can't do either of those things. APEX runs on Salesforce's servers and when you send an email it leaves that environment. The only time you can monitor a successful response is when you're dealing with an API that generates webhooks.

Sending email from Magento to fails

I am trying to send an email from a custom module in magento, however it fails to send it.
do i need to include anything or should i make some configuration with my hosting?
Here you can see my code:
$mail = new Zend_Mail();
$mail->setBodyText($mailbody);
$mail->setFrom('admin#gmail.com', 'admin');
$mail->addTo('email#gmail.com', 'client');
$mail->setSubject('Error report');
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
}
It's better to use Magento's models for sending email. This way you know it's being send correctly, and get userful errors when it fails
The most simply way:
$email = Mage::getModel('core/email_template');
$email->setSenderEmail('sender#email.com');
$email->setSenderName('name');
$email->setTemplateSubject('Subject');
$email->setTemplateText('emailbody');
$email->send('receiver#mail.com', 'receiver name');
Remember that you host my not support sending mail, or that your provider is blocking port 25. This will result in a message in your exception.log
If you want to see how the final email looks, print $email->getProcessedTemplate() onto your screen
You have to configure your smtp in php.ini
What is your provider ? It's possible to find the smtp server's url, and put it in your php.ini file.

Commit transaction then send email

In Java, let's say I have a transaction that once it is committed, I want to do another action, in this case, send an email.
Therefore,
try {
transaction.begin()
...
transaction.commit()
// point 1
Utility.sendEmail(...)
} catch (Exception e) {
transaction.rollback();
}
Is it possible for the thread to die/get killed at point 1 and not send an email ?
Any way to minimize this ? JTA + JMS perhaps, where the action of sending a message is part of a transaction ?
I'm investigating an issue and exploring whether this is possible. JVM is still alive (no OOM). I do not know the inner working of the app server so not sure if this is possible.
I can't say for sure if the rollback() in the catch clause has any effect if the commit() was OK and sendEmail() threw an exception. The quickest way to test this is to throw an exception from the sendEmail() method and see if the transaction was actually committed.
The way I would put it though, is to move the sendEmail() call away from your try block:
try {
transaction.begin()
...
transaction.commit()
} catch (Exception e) {
transaction.rollback();
}
try {
// point 1
Utility.sendEmail(...)
} catch (Exception e) {
// handle it
}
This way you can control what will happen if a rollback was made.
Also, I think that sending the email to a JMS queue is in most cases a good idea. Doing it like that will give your DB code permission to continue and supposedly give feedback to your user that everything went OK and the email will be sent whenever it fits the email controller's schedule. For example, there might be a connection issue with your email server and the email sending would hang for say 30 seconds before throwing an exception and your user would see this as a very long button click.

Zend Mail Exception - unroutable Address - why?

Hi guys I've built a simple cron program which runs in php using the zend framework. It sends emails periodically to members of a website with updates. It was working fine when all of a sudden it just dies out upon emailing to a particular email and all I get is this error message:
PHP Fatal error: Uncaught exception 'Zend_Mail_Protocol_Exception' with message 'Unrouteable address ' in /web/content/library/Zend/Mail/Protocol/Abstract.php:431
Whats going on and why is this happening for this particular email?
The email seems fine though i.e it isn't malformed or so. Also how can I prevent something like this from stopping the cron job to proceed with other emails.
What about placing it in a try catch block ?
First of all you should validate email addresses, Afterwards you should try a catch block like this:
try {
/*
* Set up Testing environment for Smtp mail
* Handle Mail exceptions Different
*/
$mail = new Zend_Mail();
$mail->send();
} catch (Zend_Mail_Transport_Exception $ex) {
$this->addError('There was an error sending e-mail to the new admin !');
} catch (Exception $ex) {
$this->addError('There was an error processing your request');
}