Sending a VF Page as Attachment in Mail through Apex Class

Rate this post

Following code can be used for sending a vf page as an attachment with an email:

public class Gene_PDF {

 public PageReference sendPdf() {
  PageReference pdf = Page.mail_pdf; //mail_pdf is the name of vf page      
  pdf.getParameters().put('email',email);      // goToNextPage('email');      
  Blob body;                      
  
  try{         
	  body = pdf.getContent();
	 } catch (VisualforceException e) {
	  body = Blob.valueOf('Some text');

	 }

 Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
 attach.setContentType('application/pdf');
 attach.setFileName('testPdf.pdf');
 attach.setInline(false);

 attach.Body = body;
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 mail.setUseSignature(false);
 mail.setToAddresses(new String[] {email});
 mail.setSubject('PDF Email Demo');
 mail.setHtmlBody('Here is the email you requested! Check the attachment!');
 mail.setFileAttachments(new Messaging.EmailFileAttachment[] {attach}); 
 // Send the email           
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });       
 ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with PDF sent to '+email));       
 return null;     
 }

}

Here:
1) mail_pdf is the visualforce page that we want to use as attachment and

2) email is a pre-acquired Email-ID from user to which the email will be sent.

Leave a Comment