Sending Email attachment by using Apex

How to send email attachment by using Apex? By using EmailFileAttachment class we can send an attachment. We can use this SingleEMailMesSage to send attachments.

Below are the methods in EmailFileAttachment class.

  • setBody(Blob) : To set the attachment.
  • setContentType(String) : To set content type of the attachment.
  • setFileName(String) : To set the attachment file name.
  • setInline(Boolean) : Used to specify content description.

See the below example to understand EmailFileAttachment:

bookdetails vf page

We will send the below Visualforce page as an attachment.

<apex:page standardController="Books__c" renderAs="pdf">
<apex:pageBlock >
<apex:pageBlockSection columns="1">
<apex:outputField Value="{!Books__c.Name}"/>
<apex:outputField Value="{!Books__c.Title__c}"/>
<apex:outputField Value="{!Books__c.price__c}"/>
<apex:outputField Value="{!Books__c.Publisher__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

attachmentExample

This controller is having logic to send attachment in an email.

public class attachmentExample{
	Books__c book;
	
	public attachmentExample() 	{
		book = [select id,name from Books__c where Id = :ApexPages.currentPage().getParameters().get('id')];
	}
	
	public pagereference sendAttach() {
		Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
		Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
		PageReference pref = page.bookdetails;
		pref.getParameters().put('id',(String)book.id);
		pref.setRedirect(true);
		Blob b = pref.getContent();
		attach.setFileName('BookDetails.pdf');
		attach.setBody(b);
		semail.setSubject('Book details');
		String[] sendTo = new String[]{'XXXXXXXXX@gmail.com'};
		semail.setToAddresses(sendTo);
		semail.setPlainTextBody('Please find the attached book details');
		semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
		Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
		return null;
	}
}

To test sending an email with an attachment, create detail button to execute above logic in object & add that button in detail page.