0% found this document useful (0 votes)
124 views

Email Handler

This Apex class handles inbound email messages by: 1. Parsing the email address to determine which org to associate the case with. 2. Creating a new case or linking to an existing case by thread ID. 3. Inserting the email and any attachments as records related to the case. 4. Sending notification emails to the case owner and sender.

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views

Email Handler

This Apex class handles inbound email messages by: 1. Parsing the email address to determine which org to associate the case with. 2. Creating a new case or linking to an existing case by thread ID. 3. Inserting the email and any attachments as records related to the case. 4. Sending notification emails to the case owner and sender.

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

global class FGS_EmailHandler implements Messaging.

InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEm
ail email, Messaging.InboundEnvelope envelope) {
EmailServiceSetting__c limerick = EmailServiceSetting__c.getInstance('
Limerick');
EmailServiceSetting__c turkey = EmailServiceSetting__c.getInstance('Tu
rkey');
EmailServiceSetting__c venrayLenovo = EmailServiceSetting__c.getInstan
ce('VenrayLenovo');
EmailServiceSetting__c venrayHP = EmailServiceSetting__c.getInstance('
VenrayHP');
EmailServiceSetting__c sbt = EmailServiceSetting__c.getInstance('SBT')
;
if(envelope.toAddress == limerick.Email_Service_Address__c){
insertCase(limerick.Case_Origin__c, limerick.Case_RecordTypeId__c, e
nvelope.fromAddress, email, envelope.toAddress);
}else if(envelope.toAddress == turkey.Email_Service_Address__c){
insertCase(turkey.Case_Origin__c, turkey.Case_RecordTypeId__c, envel
ope.fromAddress, email, envelope.toAddress);
}else if(envelope.toAddress == venrayLenovo.Email_Service_Address__c){
insertCase(venrayLenovo.Case_Origin__c, venrayLenovo.Case_RecordType
Id__c, envelope.fromAddress, email, envelope.toAddress);
}else if(envelope.toAddress == venrayHP.Email_Service_Address__c){
insertCase(venrayHP.Case_Origin__c, venrayHP.Case_RecordTypeId__c, e
nvelope.fromAddress, email, envelope.toAddress);
}else if(envelope.toAddress == sbt.Email_Service_Address__c){
insertCase(sbt.Case_Origin__c, sbt.Case_RecordTypeId__c, envelope.fr
omAddress, email, envelope.toAddress);
}
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult
();
return result;
}
private void insertCase(String origin, String rtID, String contactEmail, M
essaging.InboundEmail email, String emailServiceAddress){
Boolean newCase = true;
ID caseID;
String threadId;
threadId = RefId(email.subject);
if(threadId == null) {
threadId = RefId(email.plainTextBody);
}
if (threadId != null) {
newCase = false;
Case oCase = [Select Id, Thread_Id__c From Case Where Thread_Id__c =:t
hreadId];
caseID = oCase.Id;
}
if(newCase) {
//Insert Case
Case caseToInsert = new Case();
caseToInsert.Origin = origin;
caseToInsert.RecordTypeId = rtID;
caseToInsert.Priority = 'High';

caseToInsert.Subject = email.subject;
caseToInsert.Description = email.plainTextBody;
caseToInsert.SuppliedEmail = contactEmail;
list<Contact> relatedContacts = [select id, accountid from contact w
here email=:contactEmail];
if(!relatedContacts.isEmpty()){
//if(relatedContacts.size() == 1){//Ignore if multiple contacts
are found with the same email address
caseToInsert.AccountId = relatedContacts[0].AccountId;
caseToInsert.ContactId = relatedContacts[0].Id;
//}
}else{
Contact c = new Contact();
List<String> splittedName = email.fromname.split(' ',2);
c.FirstName = splittedName[0];
c.LastName = splittedName[1];
c.Email = contactEmail;
insert c;
caseToInsert.ContactId = c.Id;
}
//Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Case' and A
ctive = true limit 1];
//Creating the DMLOptions for "Assign using active assignment rules"
checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId = AR.id;
dmlOpts.emailHeader.triggerOtherEmail = true;
dmlOpts.emailHeader.triggerUserEmail = true;
//Setting the DMLOption on Case instance
caseToInsert.setOptions(dmlOpts);
insert caseToInsert;
Case createdCase = [select subject, casenumber, Date_Opened__c, Cont
actId, OwnerId from case where id = :caseToInsert.Id];
//Insert first inbound email message & its attachments
Id firstemID = insertEmailMessage (email, createdCase.Id, emailServi
ceAddress);
insertAttachments(email, firstemID);
//Send the first reponse email to both sender & copied persons
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage
();
/*List<String> toAddresses = new List<String>();
toAddresses.add(email.fromAddress);
mail.setToAddresses(toAddresses);*/
mail.setReplyTo(emailServiceAddress);
mail.setSenderDisplayName('Flextronics Global Services - Customer Su
pport');
//Remove the email service address from to & cc Addresses
List<String> ccAddresses = new List<String>();
for(String s : email.toAddresses){
if(s != emailServiceAddress){
ccAddresses.add(s);

}
}
if(email.ccAddresses != null){
for(String s : email.ccAddresses){
if(s != emailServiceAddress){
ccAddresses.add(s);
}
}
}
mail.setCcAddresses(ccAddresses);
mail.setTemplateId(EmailServiceSetting__c.getInstance('General').Fir
st_Response_Email_Template_Id__c);
mail.setTargetObjectId(createdCase.ContactId);
mail.setWhatId(caseToInsert.Id);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}else {
Id emID = insertEmailMessage (email, caseID, emailServiceAddress);
insertAttachments(email, emID);
Case c = [Select OwnerId, CaseNumber, Subject from Case Where Id = :
caseID];
User u = [Select Email From User Where Id = :c.OwnerId];
//New case email notification
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage
();
List<String> toAddresses = new List<String>();
toAddresses.add(u.Email);// case owner email address
mail.setToAddresses(toAddresses);
//mail.setReplyTo(emailServiceAddress);
//mail.setTemplateId(EmailServiceSetting__c.getInstance('General').N
ew_case_email_notification_Id__c);
//create the email content directly
System.debug('Instance URL '+System.URL.getSalesforceBaseUrl().toExt
ernalForm());
String messageDate;
for(Messaging.InboundEmail.Header header : email.headers){
if(header.name == 'Date'){
messageDate = header.value;
}
}
mail.setSubject('New case email notification. Case number '+c.CaseNu
mber);
String body = 'An email has been received for case '+c.CaseNumber+':
'+c.Subject+'.'+
'\n\nPlease click the link below to review the new email and respond
appropriately.'+
'\n\n'+System.URL.getSalesforceBaseUrl().toExternalForm().replace('api','')+'/'+emID+
'\n\nNOTE: It is not recommended that you forward this email because
its association with the original case may be lost.'+
'\n\nFrom: '+email.fromAddress+
'\nSent: '+messageDate+
'\nTo: '+email.toAddresses+
'\nSubject: '+email.subject+
'\n\n'+email.plainTextBody;
mail.setPlainTextBody(body);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

public static String RefId (String text1){


Integer beg;
Integer end1;
String ref ;
String Zref = '';
Integer refLenght ;
beg = text1.IndexOf('ref:');
end1 = text1.IndexOf(':ref');
beg = text1.IndexOf('ref:');
end1 = text1.IndexOf(':ref');
if (beg != -1 && end1 != -1)
return ref = text1.substring(beg, end1+4);
return ref;
}
private static void insertAttachments (Messaging.InboundEmail email, ID
parentID){
if(email.binaryAttachments != null && email.binaryAttachments.size()
> 0){
for (integer i = 0 ; i < email.binaryAttachments.size() ; i++){
Attachment attachment = new Attachment();
attachment.ParentId = parentID;
attachment.Name = email.binaryAttachments[i].filename;
attachment.Body = email.binaryAttachments[i].body;
insert attachment;
}
}
}
private static Id insertEmailMessage (Messaging.InboundEmail email, ID p
arentID, String emailServiceAddress){
EmailMessage em = new EmailMessage();
em.TextBody = email.plainTextBody;
em.Subject = email.subject;
em.ParentId = parentID;
em.Incoming = true;
if(email.toAddresses != null){
em.ToAddress = '';
for(String s : email.toAddresses){
if(s != emailServiceAddress){
em.ToAddress += s+';\n';
}
}
}
if(email.ccAddresses != null){
em.CcAddress = '';
for(String s : email.ccAddresses){
if(s != emailServiceAddress){
em.CcAddress += s+';\n';
}
}
}
em.FromAddress = email.fromAddress;
em.FromName = email.fromName;
em.MessageDate = Datetime.now();
//Creating the DMLOptions for "Assign using active assignment rules"

checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.emailHeader.triggerOtherEmail = true;
dmlOpts.emailHeader.triggerUserEmail = true;
em.setOptions(dmlOpts);
insert em;
return em.Id;
}
}

You might also like