5

I have created two objects Flight and Flight Attendant with fields name,gender,email Having lookup between them..whenever I insert Flight Attendant via Flight Object then email alert should be sent to that particular Flight Attendant..how do i achieve this? I'm a beginner in salesforce..please help

1
6

Please look at the sample code:

trigger SendEmailToAccount on Contact (after insert) {
    if(Trigger.isAfter){
        if(Trigger.isInsert ){ 
            //helper class for single email but bulk messages
            HelperContactTrigger.sendEmail(trigger.new);
        }
    }
}

public with sharing class HelperContactTrigger {
    //static method
    public static List<Contact> sendEmail(List<Contact> contacts) {

        //query on template object
        EmailTemplate et=[Select id from EmailTemplate where name=:'Sales: New Customer Email'];

        //list of emails
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

        //loop
        for(Contact con : contacts){

            //check for Account
            if(con.AccountId == null && con.Email != null){

                //initiallize messaging method
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

                //set object Id
                singleMail.setTargetObjectId(con.Id);

                //set template Id
                singleMail.setTemplateId(et.Id);

                //flag to false to stop inserting activity history
                singleMail.setSaveAsActivity(false);

                //add mail
                emails.add(singleMail);

               //This will not send email to contact  
               emails.setTreatTargetObjectAsRecipient(false);
            }
        }

        //send mail
        Messaging.sendEmail(emails);

        return contacts;
    }
}
1
  • I'm not sure if this was different when you wrote your answer, but as of right now setTreatTargetObjectAsRecipient is a method on SingleEmailMessage, not the List. So inside the if statement, the last two LOC should trade places, and emails.setTreatTarget... should be changed to singleMail.setTreatTarget... Oct 24 '16 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.