1

I'm trying to send an Email with an attachment and a template.

EmailTemplate emailTemplate = [Select Id from EmailTemplate where Name = 'Test Mail'];

List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
Messaging.EmailFileAttachment tempFileAtt = new Messaging.EmailFileAttachment();

tempFileAtt.setFileName(fileName);
tempFileAtt.setBody(pageContent);

List<String> emailIds = new List<String>();

if(emailId.contains(',')) {
    emailIds = emailId.split(',');
} else {
    emailIds.add(emailId);            
}

email.setWhatId('a0H0K00000KqqmvUAB'); //setting it to Custom Object record Id
email.setTargetObjectId(UserInfo.getUserId());
email.setSubject(fileName);
email.setTemplateId(emailTemplate.Id);
email.setToAddresses(emailIds);
email.setSaveAsActivity(false);
email.setFileAttachments(new Messaging.EmailFileAttachment[] {tempFileAtt});
allmsg.add(email);

Messaging.sendEmail(allmsg,false);

The mail is to be sent to the Id populated in one of the custom fields. I receive an email with the correct attachment but my Email Template is missing. Not sure what I'm doing wrong here.

  • The good thing is that you are receiving the email with the attachment, which means that your template does exist. Tip: query using the DeveloperName field, which is unique. – Renato Oliveira Feb 6 '18 at 13:43
  • What kind of email template is being used? (Visualforce, HTML, Text, etc). Have you tried using the DeveloperName instead of the Name field as @RenatoOliveira suggested? – Bob Lopez Feb 7 '18 at 5:13
  • @BobLopez I'm using Text template with merge fields from my custom object. And I did try using DeveloperName, not working. The body is blank. – nverm Feb 7 '18 at 6:38
  • Could you use System.debug to see if emailTemplate.Id is filled with a value, and not null? – Sander de Jong Feb 7 '18 at 9:53
  • @RenatoOliveira I am not sure that receiving the email is proof of the email template actually having been used – Sander de Jong Feb 7 '18 at 9:55

Your Answer

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

Browse other questions tagged or ask your own question.