Skip to main content
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.
53 risposte
  1. 8 mag 2017, 11:18
    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