+ Start a Discussion
Pawan RaiPawan Rai 

Send Email Using Apex Trigger

Hello every body,

I am trying to send email alert from case comment object. Please any one help me how to write the code for sending a mail using trigger.

Cory CowgillCory Cowgill

The Apex Developer Guide has this information included in it that tells you how to send an email via APEX:



Furthermore, you should create an Email Manager APEX class which would be invoked by the trigger to send the email. Encapsulate the email logic inside your EmailManger class. Also make sure to keep in mind governor limits whenever you are writing trigger code, or Apex code in general.



one example of what i have done is to send a case owner an email  when a task (created for the case) is assigned to a user :





trigger KHD_CORE_TASK_AfterUpdate on Task (after update) {
    System.debug('## Start KHD_CORE_TASK_AfterUpdate');
     KHD_CORE_TASK_TRIGGER taskTrigger = new KHD_CORE_TASK_TRIGGER(trigger.new);
    System.debug('## END KHD_CORE_TASK_AfterUpdate');
//note that this is on update but you can suit it for you

Class method : 

public void SendEmail(){
 for(Task t1 : TaskForCase){
            //the owner of the case is different from the owner of the task
            if((caseMap.get(t1.WhatId).OwnerId != null) && (t1.OwnerId != caseMap.get(t1.WhatId).OwnerId)){
                //send an email
                if(!templateList.isEmpty() && userIds.contains(caseMap.get(t1.WhatId).OwnerId)){
                    //there is a template to be used
                    System.debug('>>>>>>>>>>>>>> template used has id :' + templateList[0].Id);
                    results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    if (!results.get(0).isSuccess())                       
                        System.debug('>>>>>>>>>>>>>> Error generated when sending mail - ' + results.get(0).getErrors()[0].getMessage());
     System.Debug('## >>>>> END KHD_CORE_TASK_TRIGGER - SendEmail method  <<<<<');
the only important part is that i created a mail and send it to the case owner ,the mail use an email template with the receipient type being a user (case owner) and the the relatedTo being the Task.
hope this help you



Before you ask how i declare the mail part and the result part,here it is:


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



List<Messaging.SendEmailResult> results = new list<Messaging.SendEmailResult>();



Hello all.
I need to write test code for the trigger which sends email by updating or inserting case.

or please send me the test code of your code.the code which is here above..


Thanks in Advance



i am sending you the raw test method :


static testMethod void testSendTaskEmail(){
        System.Debug('## >>>>> testing class AP01Activites - testSendTaskEmail STARTS <<<<<'+UserInfo.getUserName());
        ID acctRecordTypeID = [Select r.id From RecordType r where DeveloperName = :system.label.RecordTypeName and Sobjecttype = 'Account' Limit 1].id;
        ID taskRecordTypeID = [Select r.id From RecordType r where DeveloperName = :system.label.RecordTypeNameTask and Sobjecttype = 'Task' Limit 1].id;
        //Create an account
        Account acc01 = new Account (Type = 'Concurrent', name = 'J.Fernandez', recordTypeID = acctRecordTypeID,Phone='+230 1111111');
        insert acc01;  
        Account acc02 = new Account (Type = 'Concurrent', name = 'TestAcc1', recordTypeID = acctRecordTypeID);
        insert acc02;       
        Contact c01 = new Contact(Lastname = 'Fernandez',AccountId = acc01.Id,Phone='230 23 234',Email='JF@gmail.fr', title='sss');
        insert c01;
        Contact c02 = new Contact(Lastname = 'testContact1',AccountId = acc01.Id,Phone='230 23 234',Email='JF@gmail.fr',mobilephone='34566');
        insert c02;
        List<Task> taskList = new List<Task> ();
        taskList.add(new Task(Subject=system.label.TaskEventCall,Priority='Medium',Status=system.label.TaskStatusNotComplete,WhatId=acc01.id,WhoId=c01.id,recordTypeID = taskRecordTypeID, Envoyer_notification__c = true));     
        taskList.add(new Task(Subject=system.label.TaskEventCall,Priority='Medium',activitydate=system.today(),Status=system.label.TaskStatusNotComplete,WhatId=acc01.id,recordTypeID = taskRecordTypeID, Envoyer_notification__c = true,Description='desc'));
        taskList.add(new Task(Subject=system.label.TaskEventCall,Priority='Medium',Status=system.label.TaskStatusNotComplete,WhatId=acc02.id,WhoId=c02.id,recordTypeID = taskRecordTypeID, Envoyer_notification__c = true));
        insert taskList;
        //now check if the field is updated accordingly
        List<Task> tList = [select Envoyer_notification__c,Mail_envoyer__c from Task where id in(:taskList[0].Id, :taskList[1].Id)] ;
        system.assertEquals(tList[0].Envoyer_notification__c, false);
        system.assertEquals(tList[0].Mail_envoyer__c, true);
        system.assertEquals(tList[1].Envoyer_notification__c, false);
        system.assertEquals(tList[1].Mail_envoyer__c, true);
        update tList;



Thanks. But i want to write test code in  ecclipse for the code below.


trigger EmailDemoSendSingle on Case (after update, after insert) {
final String template = 'Test';
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

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

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

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

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


message.setTemplateId([select id from EmailTemplate where Name =:template].id);

message1.setTemplateId([select id from EmailTemplate where Name =:template].id);

message2.setTemplateId([select id from EmailTemplate where Name =:template].id);

message3.setTemplateId([select id from EmailTemplate where Name =:template].id);

message4.setTemplateId([select id from EmailTemplate where Name =:template].id);



// Send single mail to contact of each updated case
for (Case uc: Trigger.new) {

Contact c = [select Email from Contact where Id =:uc.ContactId and Email!=null];


message.setToAddresses(new String[] {c.Email});
Messaging.sendEmail(new Messaging.Email[] {message});

for (Case vc: Trigger.new) {
IF (vc.Contactemail__c!=null){
Contact v = [select Email from Contact where Id =:vc.Contact__c and Email != null];


message1.setToAddresses(new String[] {v.Email});
Messaging.sendEmail(new Messaging.Email[] {message1});
IF (vc.Contact2email__c!=null) {
Contact b = [select Email from Contact where Id =:vc.Contact2__c and Email != null];


message2.setToAddresses(new String[] {b.Email});
Messaging.sendEmail(new Messaging.Email[] {message2});

IF (vc.Contact3email__c!=null) {
Contact d = [select Email from Contact where Id =:vc.Contact3__c and Email != null];


message3.setToAddresses(new String[] {d.Email});
Messaging.sendEmail(new Messaging.Email[] {message3});


IF (vc.Contact4email__c!=null) {
Contact f = [select Email from Contact where Id =:vc.Contact4__c and Email != null];


message4.setToAddresses(new String[] {f.Email});
Messaging.sendEmail(new Messaging.Email[] {message4});

else {



Actually i made 5 contact fields in case and want to send email to these contact(email Idz) by updating or inserting case.




Thanks in Advance


In your test class, just create some cases with the contacts fill, and insert then then update them.Note that email wont be sent to teh contacts in test classes, but in the debug log you can see the email body print out.