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
Amol DixitAmol Dixit 

Problem with opening attachment pdf sent via email service.

Hi,

 

I want to send pdf attachment through email, which will execute on E-Mail service. I wrote class for that and it is sending pdf successfully, but i am getting error while opening the pdf as,

 

"adobe reader could not open attachment.pdf becauseit is eithernot a supportedfile type or because file has been damaged (for example, it was sent as an email attachment & was't correctly decoded."

 

Please help me out. Thank you so much..

 

global class DeliverTrackerbyEmail implements Messaging.InboundEmailHandler {

global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, 
                                                  Messaging.InboundEnvelope env){

Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

String myPlainText = '';

// Add the email plain text into the local variable

try
{
      myPlainText = email.plainTextBody;
      
}
catch (System.StringException e)
{
}
 
       String fromMail=email.fromAddress;
       String submodule=myPlainText.substring(0,8);
       Resource__c res=[Select Name,Employee__r.Name__c
       From Resource__c  
       Where Employee__r.Email_ID__c = :fromMail];
       
       String ResourceNumber=res.Name;
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
     
        Resource__c ab=[select id from Resource__c where Name=:ResourceNumber limit 1];
        // Reference the attachment page and pass in the account ID
        PageReference pdf =  Page.attachmentPDF;
        pdf.getParameters().put('id',ResourceNumber); 
        pdf.setRedirect(true);

        // Take the PDF content
        Blob b = pdf.getContent();

        // Create the email attachment
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('attachment.pdf');
        efa.setBody(b);

        String addresses;
   
        String[] toAddresses = new String[]{fromMail};
        mail.setSubject( 'Tracker ' );
        mail.setToAddresses(toAddresses);
        mail.setPlainTextBody(' Hi,'+res.Employee__r.Name__c+' Please find the Attched Tracker with this mail. ');
        mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});// Sends the email 
       
   
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});   

  result.success = true;

  // Return the result for the Force.com Email Service
  return result;
}
static testMethod void testTasks() {

// Create a new email and envelope object
   Messaging.InboundEmail email = new Messaging.InboundEmail();
   Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

// Create the plainTextBody and fromAddres for the test
    email.plainTextBody = 'Here is my plainText body of the email';
    email.fromAddress ='rmencke@salesforce.com';

EmailServiceClass taskObj = new EmailServiceClass();
taskobj.handleInboundEmail(email, env);
} 


}

Thank you,

Amol Dixit

 

SRKSRK

In place of

Blob b = pdf.getContent();


u can try

Blob b = pdf.getContentAsPDF();

Amol DixitAmol Dixit

Hi, Thank you for quick response.

 

I have tried with "getContentAsPdf".

 

Now the pdf getiing open successfully. But contents are not getting into pdf, getting blank pdf. I have tried with small trial page it is working properly but in email service it is giving problem(Emplty pdf). Please help me out.

 

AttachmentPdf
<apex:page Controller="TrialController" action="{!pop}" renderAs="pdf">

<h1>Tracker Details</h1>
<apex:pageBlock >

<apex:pageBlockTable value="{!rtc}" var="item">
<apex:column value="{!item.Submodule__r.Name__c}" width="500"/>

<apex:column value="{!item.Status__c}" width="200"/>
&nbsp;&nbsp;&nbsp;
<apex:column value="{!item.Expected_Finish_Date__c}"/>

</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>



AttachmentPdf controller

public class TrialController {

    public String getStr() {
        return str;
    }


public List<Resource_Tracker__c> rtc {get;set;}
public String str=ApexPages.currentPage().getParameters().get('id');
public void pop()
{
rtc=new List<Resource_Tracker__c>();
rtc=Database.query('select Status__c,name,Resource__r.Employee__r.Name__c,Expected_Finish_Date__c,Submodule__r.Name__c from Resource_Tracker__c where Resource__r.Name=:str order by Submodule__r.Module__c');
System.debug('Size is .............'+rtc.size());
}
}


deliverTrackerAspdf Trial Page


<apex:page controller="sendEmail">
    <apex:messages />
    <apex:pageBlock title="Send an Email to Your  Representatives">
        <p>Fill out the fields below to test how you might send an email to a user.</p>

        <apex:dataTable value="{!rtc}" var="contact" border="1">
            <apex:column >
                <apex:facet name="header">Name</apex:facet>
                {!contact.Name}</apex:column>
            <apex:column >
                <apex:facet name="header">Email</apex:facet>
                {!contact.Resource__r.Employee__r.Name__c}</apex:column>
        </apex:dataTable>
    
        <apex:form ><br/><br/>
            <apex:outputLabel value="Subject" for="Subject"/>: <br/>     
            <apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
            <br/><br/>

            <apex:outputLabel value="Body" for="Body"/>: <br/>     
            <apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/>           
            <br/><br/>

        <apex:commandButton value="Send Email" action="{!send}"/> 
        </apex:form>
    </apex:pageBlock>
    </apex:page>


SendEmail Controller

public class sendEmail {
    public String subject { get; set; }
    public String body { get; set; }

    public List<Resource_Tracker__c> rtc{ get; set; }

    // Create a constructor that populates the rtc object 
    
    public sendEmail() {
    String str='R-0889';
        List<Resource_Tracker__c> rtc = Database.query('SELECT Resource_Tracker__c.Name, Resource__r.Employee__r.Name__c FROM Resource_Tracker__c where Resource__r.Name=:str');       
       //                  WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    }

    public List<Resource_Tracker__c> getrtc() {
        return rtc;
    }

    public PageReference send() {
        // Define the email 
        String str='R-0889';
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
        Resource__c ab=[select id from Resource__c where Name=:str limit 1];
        // Reference the attachment page and pass in the account ID
        PageReference pdf =  Page.attachmentPDF;
        pdf.getParameters().put('id',str);
        pdf.setRedirect(true);

        // Take the PDF content
        Blob b = pdf.getContentaspdf();

        // Create the email attachment
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('attachment.pdf');
        efa.setBody(b);

        String addresses;
   
     String[] toAddresses = new String[]{'amol_dixit@persistent.co.in'};
        // Sets the paramaters of the email 
    
        email.setSubject( subject );
        email.setToAddresses( toAddresses );
        email.setPlainTextBody( body );

        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});// Sends the email 
    
    //    Messaging.SendEmailResult [] r = 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
                    
        return null;
    }
}





 

Thank you so much.

 

 

Amol Dixit.

SRKSRK

Ok let me just share a example with u where i send a PDF as attachment in my own email service
2min

SRKSRK

Page:-- (I use the same page as dual 1st i open it without parameter p it open as normal VF & after that i pass the paramter p in URL  then it rerender as PDF

 

  

<apex:page renderAs="{!if($CurrentPage.parameters.p == null, null, 'pdf')}" controller="emailVFpage">
     <apex:pageBlock title="My Dual-Rendering Invoice">
            <apex:pageBlockSection title="Section 1"> Text </apex:pageBlockSection>
        <apex:pageBlockSection title="Section 2"> Text </apex:pageBlockSection>
    </apex:pageBlock>
             <apex:form >
              <apex:commandLink rendered="{!$CurrentPage.parameters.p == null}"  value="PDF"
             action="{!deliverAsPDF}" ></apex:commandLink> 
                 </apex:form>
</apex:page>

 

Class:-

 

 

public class emailVFpage
{
 public PageReference deliverAsPDF()
 {
 // Reference the page, pass in a parameter to force PDF
  PageReference pdf =  Page.mail_VF_as_PDF;
  pdf.getParameters().put('p','p');
   pdf.setRedirect(true);
    // Grab it!
     Blob b = pdf.getContentAsPDF();
     // Create an email
     Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
     email.setSubject('From getDeliverAsPDF!');
     String [] toAddresses = new String[] {'test_email_service@i-arvitzoh4etrxxum5wtgxxs9.9hijhea0.9.apex.salesforce.com'};
     email.setToAddresses(toAddresses);
     email.setPlainTextBody('Here is the body of the email');
         // Create an email attachment
     Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
     efa.setFileName('MyPDF.pdf'); // neat - set name of PDF
         efa.setBody(b); //attach the PDF
     email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
         // send it, ignoring any errors (bad!)
         Messaging.SendEmailResult [] r =
             Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        return null;
    }
}

 

 

 

<apex:page renderAs="{!if($CurrentPage.parameters.p == null, null, 'pdf')}" controller="emailVFpage">
     <apex:pageBlock title="My Dual-Rendering Invoice">
            <apex:pageBlockSection title="Section 1"> Text </apex:pageBlockSection>
        <apex:pageBlockSection title="Section 2"> Text </apex:pageBlockSection>
    </apex:pageBlock>
             <apex:form >
              <apex:commandLink rendered="{!$CurrentPage.parameters.p == null}"  value="PDF"
             action="{!deliverAsPDF}" ></apex:commandLink> 
                 </apex:form>
</apex:page>
amidstcloudamidstcloud
Hi Amol..

I am facing the same issue . Could You please help me with the solution . . .
Marko LamotMarko Lamot

If you havent found sollution yet...   I had a simmilar problem - despite rechecked my code for genereting PDF and sending it via email numerous times, pdf was corrupted whatever settings I've implemented...

 

There might be solution for this problem:

- "corrupted pdf" situation sometime happen of you call "send_email with render_pdf" from commandbutton from visualforce page;

- creating same button via "custom button" and putting it  on standard page layout, the problem does not occur

 

Workaround:  instead of  putting <apex:commandbutton value="Send PDF Report" action="{!SendPDFToCustomer}" /> to you visualforce page

- create "intermediate" visualforce page that would call SendPDFToCustomer:

 

 INTEMEDIATE VF Page: PDF_CUSTOMER

<apex:page standardcontroller="Case" extensions="Case_SendPDFToCustomer" action="{!SendPDFToCustomer}">


<apex:messages />
<br/>
<apex:outputLink value="/{!Case.Id}" >Return to Case</apex:outputLink>
</apex:page>                                      

 

- in your visualforcepage then call this "intermediate" visualforce page,  for example, via javascript&colon;

 

 

...
function handleSendPDFReport() { window.open("/apex/PDF_CUSTOMER?id={!Case.Id}","_top"); }
...


....
<apex:commandButton value="Send PDF Report" onclick="handleSendPDFReport()" rerender="maindetail"/>
....