Salesforce | Send email using apex code along with attachment and manage email history

Author - Shalini
28.07.2016
|
0 Comments
||

1. Send simple email using apex :

Messaging.SingleEmailMessage emailTobeSent = new Messaging.SingleEmailMessage();
List <String> listEmailMembers = new List<String>();
listEmailMembers.add('email@domain.com');
emailTobeSent.setToAddresses(listEmailMembers);
emailTobeSent.setSubject('Hi, Just Testing');
emailTobeSent.setHtmlBody('msg : ' + msg);
Messaging.SendEmailResult [] r1 = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {emailTobeSent}

2. Use template instead of manual Subject and body :

EmailTemplate et = [SELECT id,name  FROM EmailTemplate where Developername = :emailTemplate ];

Messaging.SingleEmailMessage emailTobeSent = new Messaging.SingleEmailMessage();
List <String> listEmailMembers = new List7lt;String>();
listEmailMembers.add('email@domain.com');
emailTobeSent.setToAddresses(listEmailMembers);
emailTobeSent.setTemplateId(et.id);
emailTobeSent.setTargetObjectId(UserInfo.getUserId());
Messaging.SendEmailResult [] r1 = Messaging.sendEmail(new messaging.SingleEmailMessage[] {emailTobeSent}

setTargetObjectId: Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.

3. Add attachment in email :

To add attachment in email Include following code :

Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType('application/pdf');
attach.setFileName('Myfile.pdf');
attach.setInline(false);
attach.Body = Blob.valueOf('Some Text');;
mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });

4. Manage Email History under activity history of the object :

Messaging.SingleEmailMessage emailTobeSent = new Messaging.SingleEmailMessage();
List <String> listEmailMembers = new List<String>();
listEmailMembers.add('email@domain.com');
emailTobeSent.setToAddresses(listEmailMembers);
emailTobeSent.setTemplateId(et.id);
emailTobeSent.setTargetObjectId(ContactId);
emailTobeSent.saveAsActivity = true;
emailTobeSent.setWhatId(whatId)
 
Messaging.SendEmailResult [] r1 = Messaging.sendEmail(new messaging.SingleEmailMessage[] {emailTobeSent}

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *