This is the first bit of code I have written using APEX so am learning... know a bit of Java (to a graduate level) but I don't know why this is not working.
I know that it is not giving an error to salesforce as before it was telling me (hence the commented out debug at the end. I change a contacts email and it just does it, but I receive no emails! Here is the code and thank you for any help!
trigger Test1 on Contact (after update) {
//IF Email has changed (look at the old email and compare to new)
if(trigger.old[0].Email != trigger.new[0].Email){
//Commit current transaction, reserver email capacity
Messaging.reserveSingleEmailCapacity(1);
//Create an email message object
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
//List<Messaging.SendEmailResult> results = new list<Messaging.SendEmailResult>();
//hold email address
String[] toAddresses = new String[] {trigger.new[0].Email};
//Assign new address string
mail.setToAddresses(toAddresses);
//specify return ad (assuming as being sent from server)
mail.setReplyTo('XXX@example.com');
//sender name
mail.setSenderDisplayName('Mr Apex Tester');
//Subject Specification
mail.setSubject('Subjected to Learning');
//And... the content
mail.setPlainTextBody('You have just changed your SalesForce contact email from ' + trigger.old[0].Email + ' to ' + trigger.new[0].Email + '. If this was not intentional please log back into Salesforce.com and ammend you details.');
//if (!results.get(0).isSuccess()){
//System.debug('That didnt really work did it? Reason: ' + results.get(0).getErrors()[0].getMessage());
}
}
the first trouble into your code is that your trigger is not BULK read about it here
the next trouble is that you don't send email with Messaging.sendEmail
try the following:
trigger Test1 on Contact (after update) {
Messaging.reserveSingleEmailCapacity(trigger.size);
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
for (Contact c : trigger.new) { // walk through all records which is processed
Contact old = trigger.oldMap.get(c.Id); // get old record from oldMap
if (old.Email != c.Email ) { // check current email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] {c.Email};);
email.setReplyTo('XXX@example.com');
email.setSenderDisplayName('Mr Apex Tester');
email.setSubject('Subjected to Learning');
email.setPlainTextBody('You have just changed your SalesForce contact email from ' +
old.Email + ' to ' + c.Email +
'. If this was not intentional please log back into Salesforce.com and ammend you details.');
emails.add(email);
}
}
Messaging.sendEmail(emails);
}