0

This is my code to send an email in apex. I have created a text Email Template where i need to use first name from contact. How ever the {!Contact.firstname} field is not populating.When i press "send test and verify merge fields" button i am getting the desired output. How ever when i send a mail from developer console the field is not populating as desired.

2

There are few things you are doing wrong.

  1. if you are Using Template, you dont have to manually add htmlBody,subject to the Single Email Message instance.
  2. As you are sending a message to contact, you need to use setTargetObjectId instead of whoId.
  3. You are trying to send email to All contacts which will fail because of Salesforce Limits.

Your code will be like

public Static void sendMail() {

EmailTemplate et = [SELECT Id,Subject, HtmlValue, Body FROM EmailTemplate where Name = 'New'];
List<Contact> ls1 = new List<Contact>([select Id, Email, firstname from contact where some filter for sure]);
List<Messaging.SingleEmailMessage> messageList = new List<Messaging.SingleEmailMessage>();
OrgWideEmailAddress owa : [select id, Address, DisplayName from OrgWideEmailAddress limit 1];//Add ur own filter

 for(Contact c: ls1)
{
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setTargetObjectId(c.Id);
    mail.setTemplateId(et.Id);   
    mail.setOrgWideEmailAddressId(owa.id);  
    mail.setSaveAsActivity(false);
    messageList .add(mail);

}



Messaging.SendEmailResult[] results = Messaging.sendEmail(messageList);

}

setTargetObjectId(targetObjectId) : 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.

Src: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_forcecom_email_outbound.htm

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm

Make sure you have a look at APEX Email limits before going ahead with your implementation. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.