Outbound Email Service

Outbound Email Service

Sending Email
This can happen wherever Apex logic runs, essentially in triggers, email services, Visualforce controllers, and so on.

Emails sent by Force.com can be one of two types:
i. Single emails are like regular individual emails that may go to one or more addresses (to/cc/bcc), but each of these emails has the same body.
ii. Mass emails typically go to a large number of addresses (currently capped to 250 per email), with personalized message bodies.

Sending Single Emails
our first trigger sends email to the contacts for the cases using a Visualforce template. The logic here happens to be inside a trigger, but can be anywhere you execute Apex.

Email and Visualforce Template
Templates are convenient for building the messages, but they are optional: you can also directly set the message body with setHtmlBody() or setPlainTextBody()

trigger EmailDemoSendSingle on Case (after insert) {

  final String template = 'EmailDemoSendSingleTemplate';
  Id templateId; 

  try {
    templateId = [select id from EmailTemplate where Name = :template].id;
  } catch (QueryException e) {
    ...handle exception if no template is retrieved, or create condition to set email body in code
  }

  List<Messaging.SingleEmailMessage> messages = new List<Messaging.SingleEmailMessage>();
  …

During the construction of each message, you optionally call setTargetObjectId() and setWhatId() on the message if you have merge fields in the template. If you’re using a Visualforce template (such as this example), the id in setTargetObjectId() corresponds to the recipient of the email. This will allow merge fields like {!recipient.FirstName} to resolve properly. The id in setWhatId() corresponds to the object used for the relatedTo object used in the merge fields. In this example, these correspond to a Contact and Case record respectively.

// Send single mail to contact of each updated case
for (Case uc : [select ContactId, Contact.Email from Case where Id in :Trigger.new and HasOptedOutofEmail = false]) {

  Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

  message.setTemplateId(templateId);
  message.setTargetObjectId(uc.ContactId);
  message.setWhatId(uc.Id);
  …

Finally, you set the addresses (in this case just one contact per case) directly and send the email. You can specify to, cc, and bcc separately. Once complete add the new message to the list of messages to send. And “outside” of the for loop, call sendEmail() on the list.

 …
      message.setToAddresses(new String[] {uc.Contact.Email});
      messages.add(message);
    }

    Messaging.sendEmail(messages);
}

Now If you create a new Case record, the trigger will fire, which will in turn send off emails to a number of contacts, each with a personalized email generated from the Visualforce template.

Mass Email

Mass email differs from single emails mainly in the way that they specify the merge fields and addresses. The following code contains a trigger that responds to Case record updates. Unlike the previous trigger, this code will email all the contacts for the Account related to the Case.
You start by creating an instance of MassEmailMessage. As with the single email case, you select the template that has the merge fields.

rigger EmailDemoSendMass on Case (after update) {
  final String template = 'EmailDemoSendMassTemplate';
  Messaging.MassEmailMessage message = new Messaging.MassEmailMessage();
… 
  message.setTemplateId([select Id from EmailTemplate where Name = :template].Id);
  …

// Send mass email to contacts of account associated with each updated case
for (Case uc : Trigger.new) {
  Contact[] contacts = [select HasOptedOutofEmail, Id from Contact where AccountId = :uc.AccountId];
  Id[] targetObjectIds = new Id[] {};
  Id[] whatIds = new Id[] {};
 
  for (Contact c : contacts) {
      targetObjectIds.add(c.Id);
      whatIds.add(uc.Id);
  }
 
  message.setTargetObjectIds(targetObjectIds);
  message.setWhatIds(whatIds);
  … 

    …
    Messaging.sendEmail(new Messaging.Email[] {message});
  }
}

When a Case record is created and the trigger runs, a number of emails is sent out. Each email will have its own set of merge fields set, drawn from the list of IDs found in the TargetObjectIds and WhatIds lists

Examples:

public class OutboundEmailDemo1 {
    
    public static void TextDemo(){
     	Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        List<String> toAddress = new List<String>         {'sfdcmeet@gmail.com','sfdcmeet2@gmail.com'};            
        email.setToAddresses(toAddress);
        email.setPlainTextBody('test Email!'); 
      	email.setSenderDisplayName('Salesforce Support'); 
        email.setSubject('Test Email : '); 
        email.setReplyTo('vkranjithkrishnan@gmail.com');
        
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        emails.add(email);        
        Messaging.sendEmail(emails);
    }
    
    public static void HTMLDemo(){
     	Messaging.SingleEmailMessage email1 = new Messaging.SingleEmailMessage();
        List<String> toAddress = new List<String>{'sfdcmeet@gmail.com','sfdcmeet2@gmail.com'};            
        email1.setToAddresses(toAddress);
        email1.setSenderDisplayName('Salesforce Support HTML'); 
        email1.setSubject('New Case Created : '); 
        email1.setReplyTo('vkranjithkrishnan@gmail.com');
        
		email1.setHtmlBody('<h3> Ranjith</h3><font style="color:blue">This is test mail</font>');
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);    
    }
    
    public static void AttachmentDemo(){
        Messaging.SingleEmailMessage email2 = new Messaging.SingleEmailMessage();
        Contact c = [Select Id, Email From Contact Where email='sfdcmeet@gmail.com' and Phone = '(984) 040-9993'];
        String[] toAdd=new String[]{c.email};
        email2.setToAddresses(toAdd);        
        email2.setSubject('Test Email - HTML');
        email2.setHtmlBody('<h3> Hi Ranjith</h3><font style="color:blue">This is a test mail</font>');
        
        PageReference p = Page.OpportunityPage;
        Blob body = p.getContentAsPDF(); 
        
        Messaging.EmailFileAttachment attach=new Messaging.EmailFileAttachment();
        attach.setBody(body);
        attach.setFileName('Demo Opportunities');      
        
        Messaging.EmailFileAttachment[] attachments = new Messaging.EmailFileAttachment[]{attach};
    	email2.setFileAttachments(attachments);  
        
        Messaging.Email[] emails = new Messaging.Email[]{email2};
        Messaging.sendEMail(emails);
     }
    
    public static void EmailTemplateDemo(){  
        Messaging.SingleEmailMessage email3 = new Messaging.SingleEmailMessage();
        EmailTemplate et = [Select Id From EmailTemplate Where Name = 'Contact Email Template'];
        email3.setTemplateId(et.id);    
        Contact c = [Select Id, AccountId From Contact Where email='sfdcmeet@gmail.com' and Phone = '(984) 040-9993'];
        email3.setTargetObjectId(c.id);    
        email3.setWhatId(c.AccountId);      
        Messaging.Email[] emails = new Messaging.Email[]{email3};
        Messaging.sendEMail(emails);
     }
}