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:
- Make sure you have the
SendEmail
permission enabled for your user profile. - 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:
- Create a new instance of the
Messaging.SingleEmailMessage
class. - Set the recipient's email address using the
setToList()
method. - Set the subject of the email using the
setSubject()
method. - Set the body of the email using the
setBody()
method. - Set the sender's email address using the
setFromAddress()
method. - Create an array of
Messaging.SingleEmailMessage
objects and pass it to theMessaging.sendEmail()
method to send the email.
Tips and Variations:
- You can add attachments to the email by using the
addAttachment()
method. - You can set the email priority using the
setPriority()
method. - You can set the email reply-to address using the
setReplyToAddress()
method. - You can use a template to send the email by using the
setTemplateId()
method. - You can send emails in bulk by using a loop to create multiple
Messaging.SingleEmailMessage
objects.
Best Practices:
- Always test your email sending code in a sandbox environment before deploying it to production.
- Make sure to handle any exceptions that may occur during the email sending process.
- Consider using a try-catch block to catch any errors that may occur during the email sending process.
- Use a logging mechanism to track the success or failure of the email sending process.