Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound email.
You can associate each email service with one or more Salesforce-generated email addresses to which users can send messages for processing.
The general template to create the apex class for the email services is:
global class myHandler implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
return result;
}
}
Example of Email Service – Creating Contact from email
Presumption
- Subject should contain word “Create Contact”
- Body contains only Contact Name.
// Save attachments, if any
for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = c.Id;
insert attachment;
}//Save any Binary Attachment
for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
Attachment attachment = new Attachment();
attachment.Name = bAttachment.fileName;
attachment.Body = bAttachment.body;
attachment.ParentId = c.Id;
insert attachment;
}
}result.success = true;
return result;}
static testMethod void testCreateContactFrmEmail() {
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
email.subject = ‘Create Contact’;
email.plainTextBody = ‘FromEmail’;
env.fromAddress = ‘[email protected]’;
CreateContactFrmEmail creatC = new CreateContactFrmEmail();
creatC.handleInboundEmail(email, env );
}}
After creating the above Apex class, click Your Name | Setup | Develop | Email Services.
- Click New Email Service to define a new email service.
- Select above apex class, add email address from where to accept the request and activate the service.
After filling the form, click on “Save and New Email Address” then Enter the Email Address,Accept email from mail address.