Skip to content

Instantly share code, notes, and snippets.

@TonyRenHK
Last active November 15, 2016 05:42
Show Gist options
  • Save TonyRenHK/4298a08b0a480996825abb54a3639a76 to your computer and use it in GitHub Desktop.
Save TonyRenHK/4298a08b0a480996825abb54a3639a76 to your computer and use it in GitHub Desktop.
How to send email in TriggerClass in Salesforce
Rectypeid = Schema.SObjectType.Your_Object_API_Name.getRecordTypeInfosByName().get('Record Type').getRecordTypeId();
List<Your_Object_API_Name> terms= [select ownerId,Email__c from Your_Object_API_Name where id in: SID]; // SID :set ID
List <String> ToAddresses = new List <String>();
ID ownerid; // Get Owner ID
boolean Emailexist=false;
for(Your_Object_API_Name poi:terms){
if(poi.Email__c!=null){
ToAddresses.add(poi.Email__c); // Get Email address of Supplier
ownerid=poi.ownerId;
Emailexist=true;
}
}
Id templateId;// ID userid = UserInfo.getUserId();
String templateApiName = 'Email template Name'; // Set Email template
try {
templateId = [select id, name from EmailTemplate where developername = : templateApiName].id;
}catch (Exception e) {
//throw new UtilException ('[U-03] Unable to locate EmailTemplate using name: ' + templateApiName + ' refer to Setup | Communications Templates ' + templateApiName);
}//User currentUser = [SELECT Id, Email FROM User WHERE Id =:userid]; // Get User Id
for(id rid : SID){
if( Emailexist==true){
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setTargetObjectId(ownerid);
email.setToAddresses( ToAddresses );
email.setWhatId(rid );
email.setSaveAsActivity(false);
email.setBccSender(false);
email.setUseSignature(false);
email.setTemplateId(templateId);
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment