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
John Neilan 2John Neilan 2 

Send Email via Apex

Hello,

I have a bit of a unique situation.  Currently, I have an email template set up that uses a Visualforce page as the template.  The VF page is necessary because the template loops through Cases related to an Account that match a particular criteria.  I then have an Email Alert WFR set up to fire when a date is reached.  The WFR fires on the Account, and I have mutliple lookup fields on the Account to Contacts that match a particular type.  All this works fine, however, there is no tracking of the email via the Email Alert, so any email responses have to be linked back into SFDC manually.

My question is whether or not I can accomplish this same process using Apex code rather than a WFR Email Alert, and if using the code would then allow me to track responses for each Case listed in the email template, using something like the "ref: {!Case.Id}" code?  My template is below:

Email Template:
<messaging:emailTemplate recipientType="Contact"
  relatedToType="Account"
  subject="Notification - {!relatedTo.Name} - {!TODAY()}"
  replyTo="test@test.com">
  <messaging:htmlEmailBody >
    <html>
      <body>
        <STYLE type="text/css">
          TH {font-size: 11px; font-face: arial;background: #CCCCCC;
               border-width: 1;  text-align: center } 
          TD  {font-size: 11px; font-face: verdana } 
          TABLE {border: solid #CCCCCC; border-width: 1}
          TR {border: solid #CCCCCC; border-width: 1}
        </STYLE>
        <font face="arial" size="2">
          <p>Hi {!relatedTo.Contact_4__r.Name},</p>
          <p>We would like to inform you of the following issue(s) found on {!relatedTo.Name} and would appreciate your immediate attention to this matter.<br/></p>
          <table border="0" columns="2">
            <apex:variable value="{!1}" var="ViolationNum"/>
            <apex:repeat var="cx" value="{!relatedTo.Cases}">
            <apex:outputPanel rendered="{!IF(cx.Escalate_to_Client__c = TRUE && relatedTo.Client_Escalate_Date__c = cx.Client_Escalated__c,TRUE,FALSE)}">
                <tr>
                    <td colspan="2"><b><u>Violation #<apex:outputText value="{!FLOOR(ViolationNum)}"/></u></b></td>
                    <apex:variable var="ViolationNum" value="{!ViolationNum + 1}"/>
                </tr>
                <tr>
                    <td width="17%">Case Number:</td>
                    <td width="83%">{!cx.CaseNumber}</td>
                </tr>
                <tr>
                    <td width="17%">Violation Type:</td>
                    <td width="83%">{!cx.Type_of_Violation__c}</td>
                </tr>
                <tr>
                    <td width="17%">Description of Violation:</td>
                    <td width="83%">{!cx.Compliance_Violation_Description__c}</td>
                </tr>
                <br/><br/>
            </apex:outputPanel>
            </apex:repeat>
            </Table>

            Please respond to this email by 
                <b><apex:outputText value="{0, date, MMMM d','  yyyy}">
                    <apex:param value="{!CASE( MOD( TODAY() - DATE(1900, 1, 7), 7),0, TODAY() + 2,1, TODAY() + 2,2, TODAY() + 2,3, TODAY() + 2,4, TODAY() + 4,5, TODAY() + 4,6, TODAY() + 3,null)}"/>
                </apex:outputText></b>
            indicating whether the above has been resolved so that we may review and confirm complete resolution.<p/>

            Thank you for your prompt attention to this matter!<p/>
             
        </font>
      </body>
    </html>
  </messaging:htmlEmailBody> 
</messaging:emailTemplate>

 
NagendraNagendra (Salesforce Developers) 
Hi John,

Please find the sample code below for sending an email through apex

Visual Force Page:
<apex:page controller="SendEmailController">
    <apex:form >
      <apex:pageBlock title="SEND EMAIL">
        <apex:panelgrid cellspacing="2" border="0" columns="2">
            <apex:outputtext value="Email To :"></apex:outputtext>
            <apex:inputtext value="{!emailTo}" style="width: 400px"></apex:inputtext>
            <apex:outputtext value="Email Body :"></apex:outputtext>
            <apex:inputtextarea value="{!emailBody}" style="width: 400px; height: 100px"></apex:inputtextarea>
            <apex:commandbutton value="Send" action="{!sendEmail}" rerender="statusMail"></apex:commandbutton>
            <apex:outputpanel id="statusMail" layout="block">
            <strong><apex:outputtext value="{!response}"></apex:outputtext></strong>
            </apex:outputpanel>
        </apex:panelgrid>
       </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Controller:
public class SendEmailController{
    
    public String emailTo {get; set;}
    public String emailBody {get; set;}
    public String response {get; set;}
    
    public PageReference sendEmail(){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {emailTo});
        mail.setReplyTo('noreply@yourcompany.com');
        mail.setSenderDisplayName('SAMBODHI');
        mail.setSubject('Test Email');
        mail.setPlainTextBody(emailBody);
        try{
            Messaging.SendEmailResult[] resultMail = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            if(resultMail[0].isSuccess())       
                response = 'ok sent!';
            else{
                response = resultMail[0].getErrors().get(0).getMessage();
            }
        }
        catch(System.EmailException ex){
            response = ex.getMessage();
        }   
        return null;
    }
}

Hope this helps you.

Best Regards,
Nagendra.P
John Neilan 2John Neilan 2
Nagendra,

Thanks.  However, I am not looking to create a new VF page that requires a user to click to send the email.  I need to auto-launch the VF email template with a WFR, but then have any responses to that email link back to the cases that are attached to the email in the Repeat function of the VF template.