function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
krishna1krishna1 

Send Email With Attachment Using Apex

Hi,

when send email to customer add Email attachment, i know  add email attachment with visualforce page but how to add attachment with Email template, below code get only body of the email template but not images and merge fields. please guide me how to get merge fields and images in email file attachment.

My class:

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
       
      EmailTemplate et=[Select id,Subject,body,HtmlValue from EmailTemplate where name=:'Gala Thank You Letter From Payment'];

       Blob b = Blob.valueOf(et.body);
      
       Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
       efa.setFileName('attachment.txt');
       efa.setBody(b);
      
       String addresses;
      
       addresses = pmnt.pymt__Contact__r.Email;
      
       String[] toAddresses = addresses.split(':', 0);
        email.setSubject( 'Thank You For Your Donation');
        email.setToAddresses( toAddresses );
        email.setPlainTextBody( 'Thank You .');
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
        email.setSaveAsActivity(true);
        Messaging.SendEmailResult [] r =
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});


Thanks.
Ashish_SFDCAshish_SFDC
Hi Krishna, 


Need some more information on this, 

Where are the  attachments and images stored?

Are they part of the Record in Attachments related list  already?

Or are they general Attachements which can be used in every email. 

If they are general you can store them in Resources and call them in your email template. 

This functionality is achieved through Visualforce, what is that you are looking to add via APEX?


Regards,
Ashish
Ajay_SFDCAjay_SFDC
Hi Krishna ,

EmailTemplate template = [SELECT Id FROM EmailTemplate WHERE Name = 'Your Template Name' LIMIT 1];
   
    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
    efa.setFileName('PdfFile.df');
    efa.setBody(PDFBody); // PDFBody is of blob data Type 
   
   
Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
msg.setTemplateId(template.Id);
msg.setTargetObjectId('Id Value'); //  Here you can give Id of  User , Lead , Contact 
msg.setWhatId('Id value'); // Here you can give if of account ,asset, campaign ,Case , contract if TragetObject is contact

msg.setFileAttachments(new Messaging.EmailFileattachment[]{efa});
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });

Thanks ,
 Ajay
Firoz Khan 17Firoz Khan 17
Hi Krishna,

We can attach files in the Email body of the apex class with the help of the following code : -

public static Messaging.SingleEmailMessage prepareMailWithAttach(String emailTemplateName, String orgWideEmailAddressListId, String targetObjectId, String whatId, List<String> toAddresses) {
        List<EmailTemplate> emailTemplates = getEmailTemplate(emailTemplateName);
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        if(emailTemplates.size() > 0){
            message = Messaging.renderStoredEmailTemplate(emailTemplates[0].Id, NULL, whatId);
            message.setTreatTargetObjectAsRecipient(true);
            if(String.isNotBlank(orgWideEmailAddressListId)){
                message.setOrgWideEmailAddressId(orgWideEmailAddressListId);    
            }
            if(toAddresses.size() > 0){
                message.setToAddresses(toAddresses);
            }
            List<Messaging.EmailFileAttachment> emailFileAttList = getContentVers(whatId);
            if(emailFileAttList.size() > 0) {
                 message.setFileAttachments(emailFileAttList);   
            }
            message.setTemplateId(emailTemplates[0].Id); 
            message.setWhatId(whatId);
            message.setTargetObjectId(targetObjectId);
            message.setSaveAsActivity(false);
            message.setUseSignature(false);
            message.setBccSender(false); 
            
            return message;
        }
        
        return null;
    }
   
    public static List<Messaging.EmailFileAttachment> getContentVers(Id objId) {  
        List<Messaging.EmailFileAttachment> emailAttachList = new List<Messaging.EmailFileAttachment>();
        List<ContentDocumentLink> CDLs = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId =: objId];
        List <Id> CDIdList = new List <Id> ();
        
        for (ContentDocumentLink nextCDL : CDLs) {
            CDIdList.add(nextCDL.ContentDocumentId); 
        }
        List<ContentDocument> entries = [SELECT Id, Title, FileType FROM ContentDocument WHERE ContentDocument.Id IN :CDIdList];
        if(entries.size() > 0) {
            List<ContentVersion> cvList = [SELECT Id, title, VersionData, FileExtension, ContentDocumentId 
                                           FROM ContentVersion 
                                           WHERE ContentDocumentId IN:entries 
                                           And isLatest = true];
            for(ContentVersion cvObj : cvList) {
                emailAttachList.add(setEmailFileAtt(cvObj));            
            }
            return emailAttachList;
        }
        return emailAttachList;
    }
    
    public static Messaging.EmailFileAttachment setEmailFileAtt(ContentVersion cvObj) {
        Messaging.EmailFileAttachment emlAtt = new Messaging.EmailFileAttachment();
        Blob fileData = cvObj.VersionData;
        emlAtt.setFilename('Case.' + cvObj.FileExtension);
        emlAtt.setBody(fileData);
        return emlAtt;
    }