I'm trying to send an email to a user when a new custom object is created.
This currently doesn't work in the sandbox. Are there any special settings that need to be enabled or is there a bug is the code? I checked Email Administration and 'All Emails' is enabled.
Thanks for any help
P.S. I know I can also do a workflow rule, but the next step is to also send an email when deleted so need to have some code working either way.
/* Send Email to MDR when they are added to Whatever object.
*
* @author me - code taken from sfdc99.com
*/
trigger sendEmailtoEMDR on Whatever_object__c (after insert) {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for (Whatever_object__c newTT : Trigger.new) {
if (newTT.Assigned_User__r.Email != null && newTT.Assigned_User__r.FirstName != null &&
newTT.CreatedBy.Email != null && newTT.CreatedBy.FirstName != null) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> sendTo = new List<String>();
sendTo.add(newTT.Assigned_User__r.Email);
mail.setToAddresses(sendTo);
mail.setReplyTo(newTT.CreatedBy.Email);
mail.setSenderDisplayName(newTT.CreatedBy.FirstName);
List<String> ccTo = new List<String>();
ccTo.add('an_email@gmail.com');
mail.setCcAddresses(ccTo);
mail.setSubject('A new Whatever Object was assigned to you: ' + newTT.Account__r.Name);
String body ='<html><body>'+ newTT.Assigned_User__r.FirstName + ', <br><br>' +
newTT.CreatedBy.FirstName + 'assigned' + newTT.Account__R.Name + 'as a new Whatever object';
mail.setHtmlBody(body);
mails.add(mail);
}
}
Messaging.sendEmail(mails);
}
Attribution to: user91240192094
Possible Suggestion/Solution #1
Check your email settings to make sure that all types of email are enabled. Sandboxes have non-system emails, like workflow and apex email, turned off by default when they are created/refreshed.
To check your email settings, go to Setup > Email Administration > Deliverability and make sure the access level is set to All Email.
Attribution to: greenstork
Possible Suggestion/Solution #2
In your Trigger, the value of newTT
will not have access to assigned_user__r
fields. The trigger.new List only knows about the fields in Whatever_object__c, not any relationship fields, these have to be queried for as in:
Map<ID,Whatever_obj__c> woIdToWhateverMap = new Map<ID,Whatever_obj__c> (
[select id, assigned_user__r.email, assigned_user__r.firstName, ...
where id IN :Trigger.newMap.keySet()]);
Then use the map to do your test for email eligibility as in
for (Whatever_obj__c wo : Trigger.new) {
Whatever_Obj__c newTT = woIdToWhateverMap.get(wo.id);
if (newTT.Assigned_User__r.Email != null && newTT.Assigned_User__r.FirstName != null &&
newTT.CreatedBy.Email != null && newTT.CreatedBy.FirstName != null) {
... build the email
}
}
Attribution to: cropredy
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34789