Send PDF as Attachment in Visualforce Page
This blog will help you about How we can send an email with an attached file in it through Visualforce and Apex.
Here I am using two Visualforce pages, first one render as PDF and second hold the logic to send an email by using the first Visualforce page as an attachment.
AccountDetails.vfp
<apex:page standardController="Account" renderAs="PDF">
<apex:form id="thfrm">
<center style="font-size:18px;font-weight:bold">Account Details</center>
<br/>
<table>
<tr><td><b>Account Name : </b></td><td>{!Account.Name}</td></tr>
<tr><td><b>Account Phone : </b></td><td>{!Account.Phone}</td></tr>
<tr><td><b>Account Number : </b></td><td>{!Account.AccountNumber}</td></tr>
<tr><td><b>Account Website : </b></td><td>{!Account.Website}</td></tr>
</table>
</apex:form>
</apex:page>
SendAttachmentHandler.apxc
public class SendAttachmentHandler {
@RemoteAction
public static string SendAttachment(String sEmailAddress, String AccountId){
String sMessage='';
try{
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
// Replace Visualforce(AccountDetails) page with your visualforce page
PageReference pref = page.AccountDetails;
pref.getParameters().put('id',AccountId);
pref.setRedirect(true);
Blob b = pref.getContent();
attach.setFileName('Account Details.pdf');
attach.setBody(b);
semail.setSubject('Account Details');
semail.setToAddresses(new List<String>{sEmailAddress});
semail.setPlainTextBody('Please find the attached Account details');
semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
sMessage='SUCCESS';
}
catch(Exception ex){
sMessage=ex.getMessage()+'\n'+ex.getLineNumber()+'\n'+ex.getCause();
}
return sMessage;
}
}
EmailAttachment.vfp
<apex:page controller="SendAttachmentHandler" sidebar="false" showHeader="false"> <center> <P style="font-size:22px;"><u>Send PDF as Attachment in Visualforce</u></P> <input type="text" value="" id="txtEmailAddress"/><br/><br/> <input type="button" onclick="SendEmailAttachment();" value="Send"/> </center> <script> function SendEmailAttachment(){ var AccountId = '{!$CurrentPage.parameters.Id}'; var emailAddress=document.getElementById('txtEmailAddress').value; if(emailAddress!=null && emailAddress!=''){ TestHandler.SendAttachment(emailAddress,AccountId,function(result,event){ if(event.status){ if(result=='SUCCESS'){ alert('Email sent successfully.'); } else{ alert(result); } } }) } else{ alert('Please provide email address!'); } } </script> </apex:page>