+ 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)
Biswajit RajwarBiswajit Rajwar
Amazing Read. Keep up sharing ..
https://www.bigenter.info/one-word-caption/
civiconcepts12civiconcepts12
This is really good information, but as amit singh said make sure code is added as html class in file
types of doors (https://civiconcepts.com/blog/25-types-of-doors-for-your-perfect-house)
hUM rABRIhUM rABRI
This is really good information, but as amit singh said make sure code is added as html class in file
types of doors (https://civiljungle.com/types-of-doors/
Jitendra Tiwari 14Jitendra Tiwari 14
Great info, thanks for sharing it. Building Estimate (https://www.civillead.com/estimate-of-building-in-excel/)
hUM rABRIhUM rABRI

Great info, thanks for sharing it. Building Estimate  (https://bit.ly/3iWox9w)
Raja Ram 35Raja Ram 35
This is really good information, but as amit singh said make sure code is added as html class in file: Download SRS Root Apk (https://hackerztrickz.com/srsroot-apk-download/)
 
Rakesh Patel 52Rakesh Patel 52
This is really good information, but as Amit Singh said make sure code is added as HTML class in the file
types of door (
https://www.civilexperiences.com/2021/01/concrete-mix-design-as-per-is-code-easy-way-excel-sheet-download.html)
Rakesh Patel 52Rakesh Patel 52
Great info, thanks for sharing it. Building Estimate (https://www.civilexperiences.com/search/label/estimation)
hUM rABRIhUM rABRI
civiconcepts12civiconcepts12
it is can be resolved by Concrete Mix Design (https://civiconcepts.com/blog/mix-design-of-concrete) and Coarse Aggregate (https://civiconcepts.com/blog/coarse-aggregate)
Jonathan Jones 16Jonathan Jones 16
I don't know much about coding but it helps me adding code in HTML files.


About 9To5Machinery

The idea of bringing up 9To5Machinery (https://9to5machinery.com/) came to my mind when one of my friends asked me about how to use a Spray Gun. I have always been playing with machinery and thought I could use my knowledge and put it to some use for many people who are clueless or know little about machinery.
Also, a lot of products keep popping up in the market every other day, and to help people choose the best of them is something I wish to do.
Arcy DebArcy Deb
Thankyou for this article, it's very helpful for me, Thanks
Visit : For Latest Online Shopping Deals From Various Ecxommerce Like Amazon Myntra flipkart Go https://slashdeals.in/
Arcy DebArcy Deb
Thankyou for this article, it's very helpful for me, Thanks
Visit : For Latest Online Shopping Deals From Various Ecxommerce Like Amazon Myntra flipkart Go <a href="https://slashdeals.in/buy/amazon-monsoon-appliances-fest-w0PLQ" rel="nofollow ugc">Amazon Monsoon Appliances Fest</a>
Jitendra Tiwari 14Jitendra Tiwari 14
Amazing, thanks! for sharing it. Concrete Mix Ratio (https://www.civillead.com/concrete-mix-ratio/
One way and Two Way slab (https://www.civillead.com/difference-between-one-way-and-two-way-slab/)
Timmy K 7Timmy K 7
It might sound a little but offtopic but I would like to know if anyone can help me here to create a website such as https://www.trialresetter.com/. I would be more than thankful if anyone can assist me. Please contact me. Thank you in advance!
mike mahajanmike mahajan
This is just a simple way to find out with any can help to create. Types of Window (https://civiconcepts.com/blog/types-of-windows), Types of Plywood (https://civiconcepts.com/blog/types-of-plywood), Types of stoves (http://https://civiconcepts.com/blog/types-of-stoves), Types of Table (https://civiconcepts.com/blog/types-of-tables)
mike mahajanmike mahajan
Thank you for this of important article, it's very really helpful for me, Thanks Privacy fence (https://civiconcepts.com/blog/privacy-fencev), Types of Ladders (https://civiconcepts.com/blog/types-of-ladders), Types of Building (https://civiconcepts.com/blog/types-of-building), Standard Kitchen Counter Height (https://civiconcepts.com/blog/standard-kitchen-counter-height)
mike mahajanmike mahajan
Would you be able to not able to share the VF code and waht is  Apex class with me ? thanks Types of Curtains (https://civiconcepts.com/blog/types-of-curtains), Types of Houses (https://civiconcepts.com/blog/types-of-houses-in-india), Standard Window Size (https://civiconcepts.com/blog/standard-window-size), Types of Load (https://civiconcepts.com/blog/types-of-load), Queen bed Dimensions (https://civiconcepts.com/blog/queen-bed-dimensions), Rebar size (https://civiconcepts.com/blog/rebar-sizes), Tiling Tools (https://civiconcepts.com/blog/tiling-tools)
mike mahajanmike mahajan
Introduction To Stoves The stove word is derived from an Old Dutch meaning place to cook and heat. The stoves are a device that burns fuel or electricity for generating Roof Sheet types (https://civiconcepts.com/blog/roof-sheet-types) Types of clamps (https://civiconcepts.com/blog/types-of-clamps) Wall Putty (https://civiconcepts.com/blog/what-is-wall-putty) Dry wall alternatives (https://civiconcepts.com/blog/drywall-alternative) Drapes vs Curtains (https://civiconcepts.com/blog/drapes-vs-curtains) types of flase ceiling (https://civiconcepts.com/blog/types-of-false-ceiling) parking Space Dimensions (https://civiconcepts.com/blog/parking-space-dimensions) Types of ladders (https://civiconcepts.com/blog/types-of-ladders) Coffered Ceiling  (https://civiconcepts.com/blog/coffered-ceiling) Types of shovels (https://civiconcepts.com/blog/types-of-shovels
David OtangaDavid Otanga
earn money using microsoft word for free (https://latestsinfohub.com/earn-money-using-microsoft-word-for-free/)
how to activiate microsoft office without key (https://latestsinfohub.com/activate-microsoft-office/)
how to split wordpress post into multiple pages (https://latestsinfohub.com/how-to-split-your-wordpress-post-into-multiple-pages/)
how to check fesco bill online  (https://latestsinfohub.com/fesco-bill-online-how-to-check-your-bill-save-money-2022/)
ufone loan code (https://latestsinfohub.com/ufone-loan-how-to-take-loan-from-ufone-to-get-mobile-balance-for-emergency/)
pacman 30th anniversary  (https://latestsinfohub.com/pacman-30th-anniversary-the-new-google-doodle/)
solitaire cash promo code 2022 (https://latestsinfohub.com/solitaire-cash-promo-code-2021-2022-free-money-complete-guide/)
seal team season 6 release date (https://latestsinfohub.com/seal-team-season-6-release-date-everything-we-know-so-far/)
power season 7 renewed or cancelled?  (https://latestsinfohub.com/power-season-7-renewed-or-cancelled-will-there-be-another-series/)
house party walkthrough (https://latestsinfohub.com/house-party-walkthrough-complete-amys-story-walkthrough-guide-tips/)
6 ways to recover website from google may core update (https://latestsinfohub.com/6-ways-to-recover-website-from-a-google-may-core-update-guaranteed/)
what is slayers unleashed trello (https://latestsinfohub.com/what-is-slayers-unleashed-trello/)
jio rockers 2022 telugu movie download (https://latestsinfohub.com/jio-rockers-2022-telugu-movie-download-jiorockers-com/)
dior sauvage dossier co perfume review (https://latestsinfohub.com/dior-sauvage-dossier-co-perfume-review/)
jim wool roblo (https://latestsinfohub.com/jim-wool-roblox-who-is-jimwool/)x 
taylordle may  (https://latestsinfohub.com/taylordle-may-13-2022-answer-5-13-22-try-hard-guides/)
puzzle type with pictures (https://latestsinfohub.com/puzzle-type-with-pictures-crossword-clue-try-hard-guides/)
passion.io alternatives (https://latestsinfohub.com/passion-io-alternative/)
picuki instagram - is it safe?  (https://latestsinfohub.com/picuki-instagram-its-safe-can-do-wonders-heres-how-to-do-it/)
amds new enware area51 (https://latestsinfohub.com/amds-new-enware-area51-threadripper-edition/)






 
Neeraj Pathak 7Neeraj Pathak 7
Parvati and sons is a Uttarakhand-based IT Company. Parvati and sons was established in 2018 for startups, small businesses, and businesses to automate business works. Holding with this vision we had done so many projects in different cities in India. Our top services are website development, e-commerce website development, android, and IOS app development (https://www.parvatiandsons.in/). We have a dedicated team that gives 100% to deliver the most satisfying work experience to our clients.
fatima furniturefatima furniture
Thanks for your information , its really helpful !! if you need good sofa set (https://fatimafurniture.ae/product-category/living-room-furniture/sofa-set/) and other home furniture in UAE , please visit our online store for booking,......
Fsh Furniture 4Fsh Furniture 4
Thanks for yoyr post its was a wonderful and readable post , keep sharing!! If anyone searching best wardrobes (https://fshfurniture.ae/living-room-furniture/wardrobes-dubai/) and all Home furniture then please visit our online FSH Furniture store. Giving best discount to all peoples and deliver anywhere in UAE.