function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ 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.
Nand Kishor SharmaNand Kishor Sharma
We follow the right and correct techniques and technology to provide Interior designing and Turnkey Interior solutions to our customers. Being a top-notch Interior designer in Delhi, we are capable of executing any size of Design and Build office Interior projects. We do best office interior in most economical with best designing and pricing. <a href="https://www.niveeta.in" rel="dofollow"> Office Interior in Delhi NCR</a>
 
Nand Kishor SharmaNand Kishor Sharma
Dear writer Great Blog! This post gives a better idea about furniture. Thanks for sharing useful information. I hope you will like for website. Please keep sharing! Currently, I’m looking for the  With your insights, I think I would be able to choose the best one wisely
<a href="https://www.niveeta.com/office-furniture-company.html" rel="dofollow"> Office furniture company in Delhi </a>
Kamran HaiderKamran Haider
Yes, you can send the generated PDF as an email by using the Apex code in Salesforce. You can write a custom Apex class to generate the PDF and then use Salesforce's built-in email services to send the generated PDF as an attachment. You can trigger this process when the custom button is clicked by using a custom button and its associated JavaScript code.

Premium Quality Bedroom Furniture and Bed in Dubai and Uae (https://gulflinefurniture.ae/)
Ronak G 9Ronak G 9
Thanks for your information, its really helpful !! if you would like to show types of door hinges with pictures (https://ssdoorhinges.online/8-types-of-door-hinges/) click the link
Darshan Singh 22Darshan Singh 22
The Best Movingoo Packers and movers services in Margao, Goa
Movingoo is IBA Approved Packers and Movers in Margao Goa. Our aim is to provide efficient relocation of safe, fast, reliable, and affordable goods. We offer our services in Margao, Goa to ensure that your belongings arrive safely at their new homes. Movingoo packers and movers in Margao Goa offer a range of packing and moving services including home shifting, office relocation, household shifting, local/domestic moving, car & bike transportation, transport insurance, international relocation, and storage.
https://www.movingoo.in/packers-and-movers-in-margao-goa/
malay sautyamalay sautya
Very helpful information thanks for sharing - Types of Curtains (https://civilnoteppt.com/types-of-curtains/), Types of Fans (https://civilnoteppt.com/types-of-fans/), Types of Ladders (https://civilnoteppt.com/types-of-ladders/), and Best Furniture Stores (https://civilnoteppt.com/best-online-furniture-stores/).  Keep it up!!
malay sautyamalay sautya
I also like to share some articles with you - Types of Hardwood Trees (https://civilnoteppt.com/types-of-hardwood-trees/), Types of Airports (https://civilnoteppt.com/types-of-airports/), Types of Shovels (https://civilnoteppt.com/parts-and-types-of-shovels/), Types of Buildings (https://civilnoteppt.com/10-types-of-buildings/), and Types of Windows (https://civilnoteppt.com/different-types-of-windows-used-in-buildings/) Thank you.
E Online TipsE Online Tips
Thanks for sharing the information, Amit! It's essential to follow best practices while coding, and I totally agree with your suggestion. When implementing the provided code, make sure to encapsulate it within a class and use it as a method within that class. This approach promotes better organization and encapsulation of functionality, making the code more maintainable and easier to understand. Happy coding!
Working Free ChatGPT Plus Accounts (https://www.eonlinetips.com/free-chatgpt-plus-accounts/)
E Online TipsE Online Tips

Totally agreed! It's essential to use the provided code within a class as a method, not as a class itself. Organizing the code within a class structure allows for better encapsulation and object-oriented design principles. So, make sure to create a class and incorporate the code snippet into one of its methods.

Bihar Police Constable Syllabus 2023 (https://sarkari-results.in/bihar-police-constable-syllabus-exam-pattern/)

Jokoye JakartaJokoye Jakarta
Very helpful information Thanks for sharing. From now i can do my job in https://www.dewiweddings.com (https://www.dewiweddings.com/) more eazy