+ Start a Discussion
Nasif Hasnain 6Nasif Hasnain 6 

trigger - email sent for new contact

I want to write a trigger on Contact , when a contact insert an email should be sent to contact email id.

I have written the below code and when I try to create a new contact, contact is not receiving an email. Can anyone help me.

trigger conss on Contact (before insert) {
    set<id> conlist = new set<id>();
    for(contact cons : trigger.new){
       conlist.add(cons.id);
    }
    public static void emailsent(){
        list<Messaging.SingleEmailMessage> maillist = new list<Messaging.SingleEmailMessage>();
        EmailTemplate et = [select id,
                             subject,
                             body from EmailTemplate where DeveloperName = 'contact_test' ];
        contact cont = [select id,email from contact where id in : conlist];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage ();
        mail.setTemplateId(et.id);
        mail.setTargetObjectId(cont.Id);
        maillist.add(mail);
        
        if(!maillist.isEmpty()){
            Messaging.sendEmail(maillist);
        }
    }
   
}
Best Answer chosen by Nasif Hasnain 6
Maharajan CMaharajan C
Hi Nasif,

Please refer the below link:
https://www.sfdc99.com/2014/03/01/sending-emails-using-apex/

Thanks,
Maharajan.C