1

I have the following code:

    public class OrderRequestCreationEmails {
    public static void sendMail()
    { 
        Messaging.reserveSingleEmailCapacity(2);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'[email protected]'}; 

        mail.setToAddresses(toAddresses);

        mail.setReplyTo('[email protected]');

        mail.setSenderDisplayName('Mail Test');

        mail.setSubject('Success! Mail Sent');

        mail.setBccSender(false);
        mail.setPlainTextBody('BODY');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

I tried to call this function from a test as such: (I know its not an actual test, its just to see if I receive a mail).

@isTest
private class CreationEmailsTest {
    @isTest private static void sendMailTest() {
        OrderRequestCreationEmails.sendMail();
    }
}

And I haven't received the mail, no idea why?

It's an example I took from the salesforce developer guide. couldn't find any answers online...

FYI - deliverability in the sandbox is turned on, and test deliverability works

1
  • 1
    Test classes / methods do not send emails. Jul 12, 2017 at 13:07

2 Answers 2

4

Unit tests have no "side effects," because the entire transaction is rolled back at the end of the test. Absolutely nothing you do within the test will have any effect in the "real world." This includes creating, modifying, or deleting records, calling out to external systems, sending emails, leaving scheduled jobs in any of the relevant queues, etc. If you want to really send an email, you need to call it from live code, such as execute anonymous or the API. That said, the point of a unit test is to make sure the code works; if your unit test passes, as written, it means that the email would have been sent out if it had not been a unit test.

2
  • Thanks for the thorough explanation. how do you execute anonymous in eclipse? or is it only in the developer console?
    – Dana Griff
    Jul 12, 2017 at 13:25
  • @D.Griff Right-click on your project, choose Force.com > Execute Anonymous..., and you can run your code there.
    – sfdcfox
    Jul 12, 2017 at 13:40
0

To test if this method is working, you can execute this code in an anonymous window.

OrderRequestCreationEmails.sendMail();
3
  • in the developer console, or its possible via eclipse as well?
    – Dana Griff
    Jul 12, 2017 at 13:20
  • Yes, you can run it via both developer console and Eclipse.
    – Ankita
    Jul 12, 2017 at 13:31
  • In eclipse, right click on the Force.com project. Select Force.com > Execute Anonymous
    – Ankita
    Jul 12, 2017 at 13:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .