+ Start a Discussion
HanumanHanuman 

Custom button to generate the PDF and send it as email

Hi all,
When custom button in detail page of  custom object is clicked i'm generating the PDF . I want to send the generated PDF as email. Can  we do this...?
Can anyone help me over here.

Thanks in advance.
Best Answer chosen by Hanuman
Amit Singh 1Amit Singh 1
Hello,

Use below code.
 
-- JavaScript --
{!requireScript("/soap/ajax/16.0/connection.js")}
{!requireScript("/soap/ajax/16.0/apex.js")}
var a = sforce.apex.execute("SendEmail","emailPdf",{localId:"{!Application__c.Id}"});

-- Apex Class Method --
public void SendEmail(Id localId){
 Application__c inv = [Select Id, name From Application__c Where Id=:localId];
 PageReference pdf = Page.PDFpage;// Replace PdfOfInvoice with your Page which render as PDF.
 pdf.getParameters().put('id', localId);
// Blob b = pdf.getContentAsPDF();
 Blob b;
 if (Test.IsRunningTest()){b=Blob.valueOf('UNIT.TEST');}else{b = pdf.getContentAsPDF();}
 // Create Attachment Object to attach with Email
 Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
 efa.setFileName(inv.Name+'.pdf');
 efa.setBody(b);
 // Define the email
 Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
 // Sets the paramaters of the email
 email.setSubject('PDF of Invoice - '+inv.Name);
 email.setToAddresses( new List<String>{inv.Email__c} );
 //email.setbccAddresses( new List<String>{'admin@gmail.com'} );
 email.sethtmlBody('Hi '+inv.Name+',<br/><br/> '
                        +'Please find the attached Invoice.'
                        +'<br/><br/>'+'Thanks,'+'<br/>'
                        +UserInfo.getName()+'<br/>'
                        +UserInfo.getOrganizationName());
 email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

 try{
      Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
 }catch(System.Exception e){
     
 }
Let me know if this helps :)

Thanks,
Amit Singh

 

All Answers

Amit Singh 1Amit Singh 1
Hello,

Below is Sample code that I have used for the same scenarion. You need to make the modification as per your requirement like VF page name, Class Name, Method Name etc.
// Send Invoice as PDF using email to the associated client...
    @AuraEnabled
    webservice static Response_Wrapper emailInvoicePDF(Id InvoiceId){
      Freshbook__Invoice__c inv = getInv(InvoiceId);
      Response_Wrapper response;
      if(inv==null){
         response = new Response_Wrapper(false,'Insufficient Access to Invoice Object.');return  response;  
      }
      PageReference pdf = Page.PdfOfInvoice;// Replace PdfOfInvoice with your Page which render as PDF.
      pdf.getParameters().put('id', InvoiceId);
     // Blob b = pdf.getContentAsPDF();
      Blob b;
      if (Test.IsRunningTest()){b=Blob.valueOf('UNIT.TEST');}else{b = pdf.getContentAsPDF();}
      // Create Attachment Object to attach with Email
      Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
      efa.setFileName(inv.Name+'.pdf');
      efa.setBody(b);
      // Define the email
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
      // Sets the paramaters of the email
      email.setSubject('PDF of Invoice - '+inv.Name);
      email.setToAddresses( new List<String>{inv.Freshbook__Client__r.Email__c} );
      //email.setbccAddresses( new List<String>{'amit@astreait.com'} );
      email.sethtmlBody('Hi '+inv.Freshbook__Client__r.Name+',<br/><br/> '
                             +'Please find the attached Invoice.'
                             +'<br/><br/>'+'Thanks,'+'<br/>'
                             +UserInfo.getName()+'<br/>'
                             +UserInfo.getOrganizationName());
      email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
      // Sends the email
      //Response_Wrapper response;
      try{
           Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
      }catch(System.Exception e){
          if(e.getMessage().contains('SINGLE_EMAIL_LIMIT_EXCEEDED')){
              response = new Response_Wrapper(false,'SINGLE_EMAIL_LIMIT_EXCEEDED.');
          }else{
              response = new Response_Wrapper(false,'Exception Executed :'+e.getMessage());
          }
          return response;
      }
      response = new Response_Wrapper(true,'Success!');return response;
    }

Let me know if this helps :)

Thanks,
Amit Singh
HanumanHanuman
Hi Amit,
Thanks for the quick responce. while trying with above code I'm getting error as below
Error: Compile Error: unexpected token: 'Response_Wrapper' at line 3 column 23.

Can you help me over here.
HanumanHanuman
Is i'm making any mistake in the below code I was geting error. And I was unable to save the class. 
     

Application__c inv = getInv(ApplicationID);
      
      PageReference pdf = Page.PDFpage;// Replace PdfOfInvoice with your Page which render as PDF.
      pdf.getParameters().put('id', ApplicationID);
     // Blob b = pdf.getContentAsPDF();
      Blob b;
      if (Test.IsRunningTest()){b=Blob.valueOf('UNIT.TEST');}else{b = pdf.getContentAsPDF();}
      // Create Attachment Object to attach with Email
      Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
      efa.setFileName(inv.Name+'.pdf');
      efa.setBody(b);
      // Define the email
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
      // Sets the paramaters of the email
      email.setSubject('PDF of Invoice - '+inv.Name);
      email.setToAddresses( new List<String>{inv.Email__c} );
      //email.setbccAddresses( new List<String>{'admin@gmail.com'} );
      email.sethtmlBody('Hi '+inv.Name+',<br/><br/> '
                             +'Please find the attached Invoice.'
                             +'<br/><br/>'+'Thanks,'+'<br/>'
                             +UserInfo.getName()+'<br/>'
                             +UserInfo.getOrganizationName());
      email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
      // Sends the email
      //Response_Wrapper response;
      try{
           Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
      }catch(System.Exception e){
          if(e.getMessage().contains('SINGLE_EMAIL_LIMIT_EXCEEDED')){
              response = new Response_Wrapper(false,'SINGLE_EMAIL_LIMIT_EXCEEDED.');
          }else{
              response = new Response_Wrapper(false,'Exception Executed :'+e.getMessage());
          }
          return response;
      }

Can you please let me how to over come the errors and use this to my custom button.
 
HanumanHanuman
I'm getting error as below
Error: Compile Error: Method does not exist or incorrect signature: void getInv(Id) from the type sendPDFEmailClas at line 4 column 23

And yes the  button is on detail page. Below code is the javascript code for button.
{!requireScript("/soap/ajax/16.0/connection.js")}
{!requireScript("/soap/ajax/16.0/apex.js")}
var a = sforce.apex.execute("sendPDFEmailClas","emailPdf",{localId:"{!Application__c.Id}"});

Is anything wrong in my code.

Can you please let me know if did anything wrong.
Amit Singh 1Amit Singh 1
Hello,

Use below code.
 
-- JavaScript --
{!requireScript("/soap/ajax/16.0/connection.js")}
{!requireScript("/soap/ajax/16.0/apex.js")}
var a = sforce.apex.execute("SendEmail","emailPdf",{localId:"{!Application__c.Id}"});

-- Apex Class Method --
public void SendEmail(Id localId){
 Application__c inv = [Select Id, name From Application__c Where Id=:localId];
 PageReference pdf = Page.PDFpage;// Replace PdfOfInvoice with your Page which render as PDF.
 pdf.getParameters().put('id', localId);
// Blob b = pdf.getContentAsPDF();
 Blob b;
 if (Test.IsRunningTest()){b=Blob.valueOf('UNIT.TEST');}else{b = pdf.getContentAsPDF();}
 // Create Attachment Object to attach with Email
 Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
 efa.setFileName(inv.Name+'.pdf');
 efa.setBody(b);
 // Define the email
 Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
 // Sets the paramaters of the email
 email.setSubject('PDF of Invoice - '+inv.Name);
 email.setToAddresses( new List<String>{inv.Email__c} );
 //email.setbccAddresses( new List<String>{'admin@gmail.com'} );
 email.sethtmlBody('Hi '+inv.Name+',<br/><br/> '
                        +'Please find the attached Invoice.'
                        +'<br/><br/>'+'Thanks,'+'<br/>'
                        +UserInfo.getName()+'<br/>'
                        +UserInfo.getOrganizationName());
 email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

 try{
      Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
 }catch(System.Exception e){
     
 }
Let me know if this helps :)

Thanks,
Amit Singh

 
This was selected as the best answer
HanumanHanuman
Error: Compile Error: unexpected token: 'void' at line 1 column 8
 
Amit Singh 1Amit Singh 1
Please make sure that you are using above code inside class as a method not as class.

Create a class and then inside that class use the above code as class.
Venkatesh C 7Venkatesh C 7
Hi Amit,
If it possiable could you please provide me full code of this secnario like VF page , apex class.
Venkatesh C 7Venkatesh C 7
Hi Amit ,
I got it , thanks,
Ash Jones 10Ash Jones 10
Hi Amit
What is emailPDF in this code?
Krishna Ganesan 12Krishna Ganesan 12
Hi Amit - Would you be able to share the VF code and Apex class with me ? thanks 
Aman Kumar 220Aman Kumar 220
Thansk for sharing this amazing answer. also check it out.
7 Best Free VPN for Windows In Hindi (https://www.trendsduniya.in/2020/09/best-free-vpn-hindi.html)
Ankit DharmeshAnkit Dharmesh
Check Latest Updated information of Latest State and central Government schemes at 
Online Sarkari Yojana (https://www.onlinesarkariyojana.in/)
deep dkdeep dk
thanks for your valueable content and great website.
check latest governement news informations and detail of schemes at sarkari yojana news blog (https://sarkariyojnanews.com/) .
Ajay yadav 54Ajay yadav 54
Thankyou for this article, it's very helpful for me, Thanks
Visit : Website designing and digital marketing company India (https://kashidigital.in)