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
Srinivas AnnamSrinivas Annam 

generate pdf and send email with attachment that pdf to contacts related to accounts

My requirement is generate pdf and send email with attachment to contacts related to  specific or all accounts.
but i got one error ,plz can you check below code...

generatepdf:

<apex:page standardController="Account" recordSetVar="acc" renderAs="pdf">
<apex:form >
<h1 style="font-size:17px;text-align:center">PDF Generation Example</h1>
<p style="font-family:Arial,Gadget,sans-sarief;font-size:15px"> This is the Example of pfd creating pdf and integrated with Html,css Advance Example will be shown </p>
<body>
<div>
<table style="border-collapse:collapse;width=100%;font-family:rebuchet,MS,arial,sans-serief;">
<tbody style="display:table-row-group;vertical-align:middle;">
<tr style="display:table-row;">
            <th style="font-size:1 em;text-align:left;padding-top:5px;padding-bottom:4px;padding:3px 7px 2px 7px;background-color:#A7c942;color:#fff;border:1px solid #98bf21">Company Name</th>
            <th style="font-size:1 em;text-align:left;padding-top:5px;padding-bottom:4px;padding:3px 7px 2px 7px;background-color:#A7c942;color:#fff;border:1px solid #98bf21">Contact Number</th>
            <th style="font-size:1 em;text-align:left;padding-top:5px;padding-bottom:4px;padding:3px 7px 2px 7px;background-color:#A7c942;color:#fff;border:1px solid #98bf21">Compan Type</th>
          
</tr>
<apex:repeat value="{!acc}" var="a">
<tr>
<td style="font-size:1 em;border:1px solid #98bf21;padding 3px 7px 2px 7px;border-collapse:collapse;">{!a.Name}</td>
<td style="font-size:1 em;border:1px solid #98bf21;padding 3px 7px 2px 7px;border-collapse:collapse">{!a.AccountNumber}</td>
<td style="font-size:1 em;border:1px solid #98bf21;padding 3px 7px 2px 7px;border-collapse:collapse">{!a.Type}</td>
</tr>
</apex:repeat>
</tbody>
</table>
</div>
<div style="padding-top:30px;line-hieght:24px;">
<h8 style="font-size:17px;">Thanks and Regards</h8><br/>
<span style="font-size:17px;font-weight:bold;font-family:britannic bold,serif;color:#11ff11">Code</span>
<span style="font-size:17px;font-weight:bold;font-family:britannic bold,serif;color:#008899">For</span>
<span style="font-size:17px;font-weight:bold;font-family:britannic bold,serif;color:Blue">PDF Generation</span>

</div>
</body>
</apex:form>
 
</apex:page>

sendpdfemail:

<apex:page controller="pdfsendcls">
<apex:messages />
        <apex:form >
        <apex:pageBlock title="Send Email Example.Send to the related contacts Email of the Account :{!acc.Name}">
<p> This is the example of the sending email from the salesforce by generating Attachment from a visualforce page</p>
        <apex:pageBlockTable value="{!acc.contacts}" var="c"> 
                <apex:column headerValue="Name">{!c.Name}</apex:column>
                <apex:column headerValue="Email">{!c.Email}</apex:column>
        </apex:pageBlockTable>
    <apex:outputLabel for="subject" value="Subject">:<br/></apex:outputLabel>
    <apex:inputtext size="80" maxlength="80" id="subject"/><br/><br/><br/>
        <apex:outputLabel for="Body" value="Body">:<br/></apex:outputLabel>
    <apex:inputtextarea cols="80" rows="8" id="body"/><br/><br/>
    
    <apex:commandButton value="Send Email" action="{!SendEmail}"/>
</apex:pageBlock>
          </apex:form>
   </apex:page>

pdfsendcls:

public with sharing class pdfsendcls {
    public Account acc { get; set; }
    public string eSubject{get;set;}
    public string eBody{get;set;}
    public string htmlBody{get;set;} 
            public pdfsendcls(){
            //acc=[select Name,(select name,id,email from account.contacts) from account where Id =:contact.AccountId];
            acc=[select Name,(select name,id,email from account.contacts where AccountId='0012800000hlgnC') from account where Id ='0012800000hlgnC'];//:ApexPages.CurrentPage().getparameters().get('id')];
        //    acc=[SELECT Id, Name,Email FROM Account WHERE Id IN (SELECT AccountId FROM Contact WHERE Email!= null)];
        //acc=[SELECT FirstName, email from Contact where AccountID =:contact.AccountId];
            
            }

            public PageReference SendEmail(){
                Messaging.singleEmailMessage msg=new Messaging.singleEmailMessage();
                PageReference pdfexample=page.generatepdf;
                pdfexample.setRedirect(true);
                Blob b=pdfexample.getContent();
                Messaging.EmailFileAttachment fa=new Messaging.EmailFileAttachment();
                fa.setFileName('pdfAttachment.pdf');
                fa.setBody(b);
                String eaddress;
           if(acc.contacts[0].Email!=null){
                eaddress=acc.Contacts[0].Email;
                for(integer i=1;i<acc.Contacts.Size();i++){
            if(acc.contacts[i].Email!=null){
            eaddress+=':'+acc.contacts[i].Email;
                                }
            
                        }
                        system.debug('-----------+1'+eaddress);
                    }
                  String[] toAddress=eaddress.split(':',0);//new String[]{acc};
                  //toAddress.add(eaddress[i]);
                  msg.setSubject(eSubject);
                  msg.setPlainTextBody(eBody);
                  msg.setHtmlBody(htmlBody);
                  msg.setToAddresses(toAddress);
                  msg.setFileAttachments(new messaging.EmailFileAttachment[]{fa});
                  //Now sending An email...
                 Messaging.SendEmailResult[] result=Messaging.sendEmail(new Messaging.singleEmailMessage[]{msg});
                  if (result[0].success) {
                      System.debug('The email was sent successfully.');
                      } else {
                          System.debug('The email failed to send: '+ result[0].errors[0].message);
}
            return null;
            }

    
}


but when i click on submit button i got this error,any one can help me...


Visualforce Error:

Help for this Page
System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Either the plain text body or html body must be supplied.: []
Error is in expression '{!SendEmail}' in component <apex:commandButton> in page sendpdfemail: Class.pdfsendcls.SendEmail: line 41, column 1
Class.pdfsendcls.SendEmail: line 41, column 1

Thanks in Advance...
Veenesh VikramVeenesh Vikram
Hi Srinivas,

The email you are sending by code, has no body supplied to it.

So just add some body to itand the error will be gone.

Modify the method as below:
public PageReference SendEmail(){
                Messaging.singleEmailMessage msg=new Messaging.singleEmailMessage();
                PageReference pdfexample=page.generatepdf;
                pdfexample.setRedirect(true);
				htmlBody = '<b> Please Find Attached the Document.</b>';
                Blob b=pdfexample.getContent();
                Messaging.EmailFileAttachment fa=new Messaging.EmailFileAttachment();
                fa.setFileName('pdfAttachment.pdf');
                fa.setBody(b);
                String eaddress;
           if(acc.contacts[0].Email!=null){
                eaddress=acc.Contacts[0].Email;
                for(integer i=1;i<acc.Contacts.Size();i++){
            if(acc.contacts[i].Email!=null){
            eaddress+=':'+acc.contacts[i].Email;
                                }
            
                        }
                        system.debug('-----------+1'+eaddress);
                    }
                  String[] toAddress=eaddress.split(':',0);//new String[]{acc};
                  //toAddress.add(eaddress[i]);
                  msg.setSubject(eSubject);
                  msg.setPlainTextBody(eBody);
                  msg.setHtmlBody(htmlBody);
                  msg.setToAddresses(toAddress);
                  msg.setFileAttachments(new messaging.EmailFileAttachment[]{fa});
                  //Now sending An email...
                 Messaging.SendEmailResult[] result=Messaging.sendEmail(new Messaging.singleEmailMessage[]{msg});
                  if (result[0].success) {
                      System.debug('The email was sent successfully.');
                      } else {
                          System.debug('The email failed to send: '+ result[0].errors[0].message);
					}
            return null;
            }

Hope this helps!
Veenesh
Srinivas AnnamSrinivas Annam
Thanks veenesh,
But I modified code like this, then i solve that error...but anyway thanks for your responce.

<apex:inputtext size="80" maxlength="80" id="subject" value="{!esubject}"/><br/><br/><br/>
 <apex:inputtextarea cols="80" rows="8" id="body" value="{!eBody}"/><br/><br/>