I have a GUI created (not Apex) email template set up. Nothing fancy, just a few fields and some text and it ends with a URL that points to the record where the email got its data.

Is there a way to code in Apex that it selects all attachments from the attachment object that have the current record's id and attaches them to the email and then sends it?

If so, how to go about it?

1 Answer 1


You can use next code to query all the attachments related to record, and add them as email attachments:

List<Attachment> attachments = [SELECT Id,Name, Body, ContentType FROM Attachment WHERE ParentId = :record_id];
List<Messaging.EmailFileAttachment> email_attachments = new List<Messaging.EmailFileAttachment>();
for(Attachment att : attachments){
    Messaging.EmailFileAttachment email_att = new Messaging.EmailFileAttachment();
//generate email here like 
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
Id template_id =  [SELECT id, name 
                   FROM EmailTemplate 
                   WHERE developername = : templateApiName].Id;
email.setToAddresses(to_receivers);//list of email addresses
email.setCcAddresses(to_cc_receivers);//list of email addresses
email.setTargetObjectId(target_recepient_id);//Id of Lead, User or Contact if that is target object. not required
email.setWhatId(sobject_id);//Id of object that should do field merge
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

Please, check this link for another example of creating email attachment:

P.S. About using email template with apex:

  • This is good but is there a way to do this in conjunction with an existing email template
    – Apex N-u-b
    Feb 25, 2016 at 8:40
  • @ApexN-u-b thats different question, but yes. You just need to call setTemplateId with template id for mail record and call setWhatId to set object id that should be merged. here's an example: developer.salesforce.com/forums/?id=906F000000094ClIAI
    – kurunve
    Feb 25, 2016 at 8:43
  • So far so good. Now for those who are thick, how to combine the two (your code and the code in the link) into something that works?
    – Apex N-u-b
    Feb 25, 2016 at 9:08
  • @ApexN-u-b updated code
    – kurunve
    Feb 25, 2016 at 9:16
  • Thanks for combining them. I tried it out. I get an error "INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds" it appears to be a bug that one can not use setWhatId with a userid. There are some work arounds but I am not sure how to implement. It doesn't merge the fields. If you have experience how to get it to merge and can explain it great. If not, many thanks for your help. It was fun trying.
    – Apex N-u-b
    Feb 25, 2016 at 15:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .