Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Salesforce by (13.1k points)
I was trying with a code for sending mails using Apex. The code is working but it is not able receive any mails? Can anyone help me with this?

1 Answer

0 votes
by (26.7k points)

So, basically you are not using the function called Messaging.sendEmail to send an email. Try the below code:

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('[email protected]');

                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);

    }

I hope this will help.

Want to know more about Apex? Prefer this tutorial on batch apex in salesforce.

Want to become a Salesforce expert? join salesforce lightning training now!!

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...