[SalesForce] Email Button – Email Template

I would like to create a custom button in the Contact detail page that when we click on it, it sends an email template capturing the information of that paricular contact.

How can I do this? Any code would be very much appreciate it!

Thanks!

Best Answer

Salesforce.com has specifically prevented us developers from having an easy time using the standard interface to send emails without user intervention. We can create a link to go to the Send Email page, but the user still has to click on Send to send the email. Here's the link:

/_ui/core/email/author/EmailAuthor?p2_lkid={!Contact.Id}&rtype=003&retURL=%2F{!Contact.Id}&template_id=00X300000000000

Simply go to Setup | Customize | Contacts | Buttons, Links, and Actions, and create this as a new button or link of the "URL" type (you can use the same window). Change the Template ID to match the email template you'd like to auto-select.

If you want a one-click send feature, you'd need Visualforce.

Update

Here's a sample Visualforce page:

<apex:page standardController="Contact" extensions="sendEmail" action="{!sendEmail}">
    <apex:pageMessages />
</apex:page>

And associated controller:

public with sharing class sendEmail {

    ApexPages.StandardController controller;

    public sendEmail(ApexPages.StandardController controller) {
        this.controller = controller;
    }

    public PageReference sendEmail() {
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setTemplateId('00X30000000h4jF');
        message.setTargetObjectId(controller.getId());
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message });
        return controller.view();
    }

}

Be sure to use "GET CSRF protection" on the page to prevent spoofing. Set the button or link behavior to "display in existing window without header or sidebar". From the user's perspective, it is nearly instantaneous.

Finally, you could also use the AJAX Toolkit's sforce.connection.sendEmail, but this will use API calls unnecessarily (but also avoid the white page flicker of the Visualforce solution).

Updated: I added the actual logic to send an email.

Updated: Here's a JavaScript-only version. Note that this will use API calls in addition to Mass Email limits, while Visualforce will only use Mass Email limits.

{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}
(function() {
sforce.connection.sessionId = "{!$Api.Session_ID}";
var message = new sforce.SingleEmailMessage();
message.replyTo = "{!$User.Email}";
message.targetObjectId = "{!Contact.Id}";
message.templateId = "00X30000000h4jF";
var result = sforce.connection.sendEmail([message]);
  if(result[0].success) {
     alert("I sent the email as you requested, master.");
  } else {
     alert("I had a booboo.");
  }
}());
Related Topic