Attach Base64 String as Salesforce Email Attachment

Attach Base64 String as Salesforce Email Attachment

EncodingUtil.base64Decode() can be used to convert Base64 String to Blob value. Then, the blob value can be used in the Messaging.EmailFileAttachment to attach attachment to the Email. 

Sample Code:

List < Messaging.SingleEmailMessage > listMessages = 
    new List < Messaging.SingleEmailMessage >();
Messaging.SingleEmailMessage objMessage = 
    new Messaging.SingleEmailMessage();
Messaging.EmailFileAttachment objAttachment = 
    new Messaging.EmailFileAttachment();
objAttachment.setContentType( 
    'application/pdf' 
);
objAttachment.setFileName( 
    'Sample.png' 
);
Blob emailBody = EncodingUtil.base64Decode(
    '<Base64 String>'
);
objAttachment.Body = emailBody;
objMessage.setToAddresses( 
    new String[] { '<Email Address>' } 
);
objMessage.setSubject( 'Image Attachment' );
objMessage.setHtmlBody( 
    'Please check the attached Image' 
);
objMessage.setFileAttachments(
    new Messaging.EmailFileAttachment[] { 
        objAttachment 
    } 
); 
listMessages.add( 
    objMessage 
); 
Messaging.sendEmail( 
    listMessages 
);

Leave a Reply