How to send mail apex

In Salesforce, you can send an email using Apex by using the Messaging.SingleEmailMessage class. Here's a step-by-step guide:

Prerequisites:

  1. Make sure you have the SendEmail permission enabled for your user profile.
  2. Create a new Apex class or modify an existing one to contain the email sending logic.

Example Apex Code:

public class SendEmailExample {
    public static void sendEmail() {
        // Create a new email message
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        // Set the recipient's email address
        mail.setToList(new String[] {'[email protected]'});

        // Set the subject of the email
        mail.setSubject('Test Email from Apex');

        // Set the body of the email
        mail.setBody('This is a test email sent from Apex');

        // Set the sender's email address
        mail.setFromAddress('[email protected]');

        // Send the email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
}

How it works:

  1. Create a new instance of the Messaging.SingleEmailMessage class.
  2. Set the recipient's email address using the setToList() method.
  3. Set the subject of the email using the setSubject() method.
  4. Set the body of the email using the setBody() method.
  5. Set the sender's email address using the setFromAddress() method.
  6. Create an array of Messaging.SingleEmailMessage objects and pass it to the Messaging.sendEmail() method to send the email.

Tips and Variations:

Best Practices: