Sending Emails from Apex

Sending Emails from Apex in Salesforce

Salesforce allows administrators to send emails based on workflow actions that are triggered within the environment. You can perform the same functionality utilizing Apex trigger code after you set your trigger logic. In this example we are going to send an email to an Account Owner once an Opportunity has been created for their Account.

We will cover the following functionality:

  • Querying the Account object for the Owner
  • Querying for the required Email Template
  • Establishing the email
  • Sending the email

 

//list for emails
List emails = new List();

//query email template object
EmailTemplate et=[Select id from EmailTemplate where name=:’Hello World’];

//query Account object
Account a = [SELECT Id, OwnerId from Account where Id =: o.AccountId];

//sending email
Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
singleMail.setTargetObjectId(a.OwnerId);
singleMail.setTemplateId(et.Id);
singleMail.setSaveAsActivity(false);
singleMail.setSenderDisplayName(‘Salesforce.com’);
emails.add(singleMail);
Messaging.sendEmail(emails);

Leave a Reply

Your email address will not be published. Required fields are marked *