Tuesday 17 May 2016

write a class and trigger to send an email after creating a patient record and once appointment has been created it should send an email.In this we have query Email Templates and we have to  fetch all the Email Id to send email.


CLASS:

public with sharing class Appointmenttriggerhandler{
public static void sendemailtoPatient(list<Appointment__c> appointments){
EmailTemplate et=[Select id from EmailTemplate where name='Appointment: New Customer Email'];
list<Messaging.SingleEmailMessage> emails = new list<Messaging.SingleEmailMessage>();
//To store patient Id
set<Id> setPatientId = new set<Id>();
if(appointments.size()> 0) {
for(Appointment__c iterator : appointments) {
if(iterator.Patient__c != null) {
setPatientId.add(iterator.Patient__c);
}
}
}
//fetch the patient records for whom an email needs to be sent
if(setPatientId.size()>0) {
list<Patient__c> Patients = [Select Id,Email__c from Patient__c where Id IN : setPatientId];
for(Patient__c pat : Patients){
if(pat.Email__c != null){
Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
singleMail.toaddresses(pat.Email__c);
singleMail.setTemplateId(et.Id);
emails.add(singleMail);
}  
}
}
Messaging.sendEmail(emails);
}
}

TRIGGER:

trigger SendEmailToPatients on Appoinments (after insert) {
    if(Trigger.isAfter){
        if(Trigger.isInsert ){ 
            
            Appointmenttriggerhandler.sendEmail(trigger.new);
        }
    }
}

No comments:

Post a Comment