Hello Everyone, In this tutorial, I am going to show, How you can send an email with an attached file in it through Visualforce and Apex. Here I give a complete example and sample code that helps you to do this task very easily in Salesforce. In this section, you will see how I generate PDF dynamically and sent it as an attachment using Apex Messaging class.

After completing this unit, you’ll able to,
  • Send PDF as Attachment in Visualforce 
So let's get started,

In this example, 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. Let's all these processes in steps,

Step 1:  Login to your Salesforce Org. and open Developer Console.

Step 2: Go to File>New>Visualforce Page and create a new Visualforce Page called AccountDetails and replace the following markup.

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>
Step 3: Go to File>New>Apex Class and create an Apex controller called SendAttachmentHandlerReplace the following code.

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;
    }
 }
Step 4: Go to File>New>Visualforce Page and create a new Visualforce Page called EmailAttachment and replace the following markup.

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!=''){
            SendAttachmentHandler.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>
Step 5: Preview EmailAttachment Visualforce page to verify it.


After previewing, your visualforce page will look like the above screenshot. Don't forget to provide an Account Id in URL as a parameter so that your PDF will bind with account record and then enter an email address in the text box and click on Send button, Hopefully you all get an success message.


Output:
See also:

Conclusion:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.