What is an Inbound Email handler ?
Inbound Email Handler is an Email Service in Salesforce implemented using Apex and is an alternative to Email-To-Case.
Why Inbound Email handler ?
When we need to perform other operation after creating a Case or if we need to perform certain operation on a existing Case. For example creating a child Case record or updating an already existing Case with an attachment/reply.
The Standard Email-To-Case is limited to Case where the Inbound Email Handler can be used with any Standard/Custom Objects.
The statement above is also the difference between email to case and apex email service.
Examples :-
global class ContactInboundEmailHandler implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope env){
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
Contact con = new Contact();
con.LastName = email.plainTextBody;
con.Email = env.fromAddress;
try{
insert con;
result.success=true;
}catch(System.Exception e){
result.success=false;
}
System.debug(‘Contact Created’ + con.Id);
//Processing Attachments
List<Attachment> lstAttachments = new List<Attachment>();
//Text Attachment
if(email.TextAttachments != Null && email.TextAttachments.size() > 0){
for(Messaging.InboundEmail.TextAttachment textAttachment: email.TextAttachments){
Attachment attachment = new Attachment();
attachment.name = textAttachment.fileName;
attachment.body = blob.valueof(textAttachment.body);
attachment.parentId = con.Id;
lstAttachments.add(attachment);
}
}
//Binary Attachment
if(email.BinaryAttachments != Null && email.BinaryAttachments.size() > 0){
for(Messaging.InboundEmail.binaryAttachment binaryAttachment: email.BinaryAttachments){
Attachment attachment = new Attachment();
attachment.name = binaryAttachment.filename;
attachment.body = binaryAttachment.body;
attachment.parentId = con.Id;
lstAttachments.add(attachment);
}
}
if(!lstAttachments.isEmpty()){
insert lstAttachments;
}
return result;
}
}