public static List<String> toAddresses = new List<String>();
/** to cache transaction data and reduce SOQLs
*/
public static List<String> getNotificationEmailAddress() {
if( toAddresses == null || toAddresses.size() == 0 ) {
Profile sysAdminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' limit 10];
List<User> sysAdmins = [SELECT id, Email FROM User WHERE ProfileId = :sysAdminProfile.id];
for( User sysAdmin : sysAdmins ) {
toAddresses.add ( sysAdmin.Email );
}
}
return toAddresses;
}
public static void sendMail(String subject, String body, List<String> recipients) {
try {
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = recipients;
message.optOutPolicy = 'FILTER';
message.subject = subject;
message.plainTextBody = body;
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
if (results[0].success) {
System.debug(LoggingLevel.INFO, 'The email was sent successfully . to ' + recipients + ' subject ' + subject );
} else {
System.debug(LoggingLevel.ERROR, 'The email failed to send: ' + results[0].errors[0].message + ' to ' + recipients + ' subject ' + subject );
}
} catch(Exception e) {
System.debug(LoggingLevel.ERROR, 'The email failed to send: ' + ' to ' + recipients + ' subject ' + subject + ' body ' + body );
System.debug( e.getMessage() + '\n' + e.getStackTraceString() );
}
}
sendMail('test email','test body', new List<String> { 'chintanjshah@gmail.com' } );
sendMail('test email 2','test body 2', getNotificationEmailAddress() );
Monday, August 14, 2017
Salesforce send admin email for error/success
Simple reference code for sending success/failure email in Salesforce
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment