Recipes by Category

App Distribution (2) Bundle logic, interface and services for distribution. App Logic (37) The Apex programming language, workflow and formulas for logic. Collaboration (5) The Salesforce Chatter collaboration platform. Database (29) Data persistence, reporting and analytics. Integration (33) Web Service APIs and toolkits for integration. Security (9) Platform, application and data security. Tools (4) Force.com tooling User Interface (36) Visualforce MVC and metadata-drive user interfaces. Web Sites (12) Public web sites and apps with optional user registration and login.
Beta Feedback
Cookbook Home » Creating Email Templates and Automatically Sending Emails

Creating Email Templates and Automatically Sending Emails

Post by Developer Force  (2010-07-16)

Status: Certified
Level: novice

Problem

You want to send an automatic email response to the job applicant's incoming email message.

Solution

  1. Create an appropriate email template through the email template wizard. Salesforce.com supports multiple email template types. This examples assumes you are using a Visualforce email template. To create a Visualforce email template, you must have the “Customize Application” permission enabled.
  2. Send an automatic email response to the job applicant's incoming email using the Messaging.sendEmail static method to process outbound email messages.
First, create a Visualforce email template:
  1. Click Setup | Email | My Templates. If you have permission to edit public templates, click Setup | Communication Templates | Email Templates.
  2. Click New Template.
  3. Choose Visualforce and click Next.
  4. Choose a folder in which to store the template.
  5. Select the Available For Use checkbox if you would like this template offered to users when sending an email.
  6. Enter an Email Template Name.
  7. If necessary, change the Template Unique Label.
  8. Select an Encoding setting to determine the character set for the template.
  9. Enter a Description of the template. Both template name and description are for your internal use only.
  10. Enter the subject line for your template in Email Subject.
  11. In the Recipient Type drop-down list, select the type of recipient that will receive the email template.
  12. Optionally, in the Related To Type drop-down list, select the object from which the template will retrieve merge field data.
  13. Click Save.
  14. Click Edit Template.
  15. Enter markup text for your Visualforce email template.
  16. Click Save to save your changes and view the details of the template, or click Quick Save to save your changes and continue editing your template. Your Visualforce markup must be valid before you can save your template.
    The maximum size of a Visualforce email template cannot exceed 1 MB.

This sample Visualforce email template creates an interview invitation:

<messaging:emailTemplate subject="Received your resume" 
    recipientType="Contact" relatedToType="Job_Application__c">

<messaging:plainTextEmailBody >
Dear {!relatedTo.Candidate__r.First_Name__c}  
        {!relatedTo.Candidate__r.Last_Name__c}

Thank you for your interest in the position 
        {!relatedto.Position__r.name}

We would like to invite you for an interview. 
Please respond to the attached invitation.

Regards,
Company
</messaging:plainTextEmailBody>


<messaging:attachment filename="meeting.ics" 
        renderAs="text/calendar; charset=UTF-8; method=REQUEST">
BEGIN:VCALENDAR
METHOD:REQUEST
BEGIN:VTIMEZONE
TZID:(GMT-08.00) Pacific Time (US and Canada)
BEGIN:STANDARD
DTSTART:16010101T020000
TZOFFSETFROM:-0700
TZOFFSETTO:-0800
RRULE:FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=11;BYDAY=1SU
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:16010101T020000
TZOFFSETFROM:-0800
TZOFFSETTO:-0700
RRULE:FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=3;BYDAY=2SU
END:DAYLIGHT
END:VTIMEZONE
BEGIN:VEVENT
DTSTAMP:20090921T202219Z
DTSTART;TZID="(GMT-08.00) Pacific Time 
        (US and Canada)":20090923T140000
SUMMARY:Invitation: Interview Schedule @ Wed Sep 23 2pm - 4pm 
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;
        CN="{!recipient.name}":MAILTO:{!recipient.email}
ORGANIZER;CN="John.Smith":MAILTO:recruiter@company.com
LOCATION:Hawaii 
DTEND;TZID="(GMT-08.00) Pacific Time 
        (US and Canada)":20090923T160000
DESCRIPTION: You are invited to an inverview
        \NInterview Schedule
        \NWed Sep 23 2pm - 4pm 
        (Timezone: Pacific Time) \NCalendar: John Smith 
        \N\NOwner/Creator: recruiter@company.com   
        \NYou will be meeting with these people:
        CEO Bill Jones, 
        Office Manager Jane Jones
\N
SEQUENCE:0
PRIORITY:5
STATUS:CONFIRMED
END:VEVENT
END:VCALENDAR

</messaging:attachment>

</messaging:emailTemplate>

Then, send an automatic email response to the job applicant's incoming email. This example uses a Visualforce email template:

emailHelper.sendEmail(myContact[0].id, newCandidate[0].id);
  // In a separate class so that it can be used elsewhere
Global class emailHelper {

public static void sendEmail(ID recipient, ID candidate) {

  //New instance of a single email message
 Messaging.SingleEmailMessage mail = 
            new Messaging.SingleEmailMessage();
 
// Who you are sending the email to
   mail.setTargetObjectId(recipient);

   // The email template ID used for the email
   mail.setTemplateId('00X30000001GLJj');
          
   mail.setWhatId(candidate);    
   mail.setBccSender(false);
   mail.setUseSignature(false);
   mail.setReplyTo('recruiting@acme.com');
   mail.setSenderDisplayName('HR Recruiting');
   mail.setSaveAsActivity(false);  
 
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }  
}

Discussion

  • You can use merge fields in Visualforce email templates. Merge fields are placeholders for data that will be replaced with information from your records, user information, or company information.
  • To check email delivery status, see “Requesting an Email Log” in the Salesforce.com online help.
  • For a complete example containing code from all the email recipes, see Email Recipes—Complete Code Example.

Share

Recipe Activity - Please Log in to write a comment

What if you dont' want to send the email automatically upon trigger, instead  you want to be prompted to send a certain templated email. Is there a way to get a task or something that upon a trigger it prompts you to send an email and the email template is attached, so that you can edit, review and send?

by a093000000XahWF  (2013-09-17)

Just wondering if there are any email templates app for ipad that I can use for sending emails.

by robert sathe  (2013-05-31)

The thing is that this article doesn't explain how to do that trigger, just the utility class that you need to create and then use in your trigger.

See how the problem says: "You want to send an automatic email response to the job applicant's incoming email message.".

by Salvador Mora  (2012-06-05)

I've used part of this code but there's some oddities.
code reads values from Case
depending on state/province of related account, reason and detail determines which of 14 templates to send.

Trigger firing (before update) produces an email but does not log the activity - mail.setSaveAsActivity(true);
Trigger firing (after update) produces 3 messages in my inbox, 1 from me as the sender (BCC on all turned on), 2 from the address provided in my code.

It appears the triggers fire twice during the save?

Back to the drawing board.

by bouscal  (2012-06-01)

 I am trying to have salesforce generate a compliance/archiving email for any post or comment made in Chatter.  I assume creating FeedComment and FeedItem Triggers is the best approach for this.  Does anyone have any sample code as I am not an experienced APEX Developer.

by a0930000008PYS4  (2011-03-11)

 sonninho - sorry - had a little glitch in our import system - it's fixed now.

by Jon Mountjoy  (2011-01-17)

I agree with sonninho - the example does not cover all the process suggested by the title.  Where is the info about sending the template 'automatically?  I assume a work flow or trigger would be needed to actually use a VF template - one that detected the creation of a new email message with realtionship to a specific object.

by sweeper  (2010-12-27)

 @Developer Force: again, this example DOES NOT make sense? Can you please check this article before publishing? I wonder what status "Certified" really mean here?!!!!

by sonninho  (2010-12-01)

X

Vote to Verify a Recipe

Verifying a recipe is a way to give feedback to others and broaden your own understanding of the capabilities on Force.com. When you verify a recipe, please make sure the code runs, and the functionality solves the articulated problem as expected.

Please make sure:
  • All the necessary pieces are mentioned
  • You have tested the recipe in practice
  • Have sent any suggestions for improvements to the author

Please Log in to verify a recipe

You have voted to verify this recipe.