+ Start a Discussion

Apex Trigger

Hello ...Hi ALL,



I just want to know is it possible to send an email through Apex trigger?If so

can u give me the example?



Scenario of mine is:If  contact is created ,i have to send an email to that contact ?through trigger



Thanks in Advance





Ys you can create a trigger to send email

I am attaching a sample trigger which sends a mail after task is closed


trigger TriggerEmail on Task (before update,after update) {

    id theownerid = Trigger.new[0].OwnerId;
    id thecreatebyid = Trigger.new[0].CreatedById;
    string theCreatedByeMail;
    string theOwnerName;

if((Trigger.old[0].IsClosed == false)&& (Trigger.new[0].Isclosed == true))
    //Task has just been closed
    User [] thecreator;
    thecreator = [select id,email from user where id=: thecreatebyid];
    theCreatedByeMail = thecreator[0].email;
    User[] theowner;
    theowner = [select id,name,email from user where id=:theownerid];
    theOwnerName = theowner[0].name;
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
    String[] toAddresses = new String[] {'test@gmail.com'}; 
    email.setToAddresses(toAddresses );
    email.setSubject('PS opp Closed');
    email.setPlainTextBody('Task has been Completed'); 
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email }); 



Find below a sample trigger which sends an email to the contact after the contact is created :


                                                                trigger Contrigger on Contact (after insert,before update)


                                                                   Contact con = trigger.new[0];

                                                                   Id contactid = con.id;

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


                                                                                String[] toAddresses = new String[] {con.email};

                                                                                email.setToAddresses(toAddresses );


                                                                   // email.setSenderDisplayName(theOwnerName);

                                                                                email.setSubject('Creation of new contact');

                                                                                email.setPlainTextBody('contact has been Created');

                                                                                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });




Did this answer your question? if so, please mark it solved.