[SalesForce] send email through trigger whenever students record is created

trigger send_notification on students__c (after insert,after update) {

    students__c std = trigger.new[0]; 
    std  = [SELECT id, Course_Name__r.OwnerID FROM students__c  WHERE Id IN: std ];
    EmailTemplate et=[Select id from EmailTemplate where DeveloperName=:'info_to_Instructor'];
    String[] toAddresses = new String[] {std.Course_Name__r.instructor__r.email__c}; 
    String[] ccAddresses = new String[] {'**'};
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    mail.setTargetObjectId(std.Course_Name__r.OwnerID);
    mail.setSenderDisplayName('TeacherPortal');
    mail.setUseSignature(false);
    mail.setBccSender(false);
    mail.setSaveAsActivity(false);
    mail.setToAddresses(toAddresses);
    mail.setCcAddresses(ccAddresses);
    mail.setTemplateId(et.id);


    if(Trigger.isAfter){
        if(Trigger.isInsert ){ 
            if(std.Course_Name__c != null) {
                //EmailTemplate et=[Select id from EmailTemplate where DeveloperName=:'info_to_Instructor'];
                //mail.setTemplateId(et.id);
                Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});   
            } 

        }
   }
}

Error: Invalid Data. Review all error messages below to correct your
data. Apex trigger send_notification caused an unexpected exception,
contact your administrator: send_notification: execution of
AfterInsert caused by: System.EmailException: SendEmail failed. First
exception on row 0; first error: INVALID_TYPE_FOR_OPERATION, Only
User, Contact, Lead, or Person objects are allowed for targetObjectId:
a0W9000000SNGdQ.: [targetObjectId, a0W9000000SNGdQEAX]:
Trigger.send_notification: line 22, column 1

Best Answer

You need to query inorder to get relation ship field value

students__c std = trigger.new[0];
std  = [SELECT id, Course_Name__r.OwnerID FROM students__c  WHERE Id IN: std.Id ];

and then use mail.setTargetObjectId(std.Course_Name__r.OwnerID);

Note: This will not work for bulk record. Please update your code for bulk operation.

Related Topic