Apex_mail example
Apex Mail is a powerful tool in Salesforce that allows you to send emails programmatically from your Apex code. Here's an example of how you can use Apex Mail to send an email:
Example: Sending a simple email
// Define the email properties
String toAddress = '[email protected]';
String subject = 'Test Email';
String body = 'This is a test email sent from Apex!';
// Create a new email message
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Set the email properties
mail.setToList(new String[] {toAddress});
mail.setSubject(subject);
mail.setBody(body);
// Send the email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
In this example, we define the email properties (to address, subject, and body) and create a new Messaging.SingleEmailMessage
object. We then set the email properties using the setToList
, setSubject
, and setBody
methods. Finally, we send the email using the Messaging.sendEmail
method.
Example: Sending an email with attachments
// Define the email properties
String toAddress = '[email protected]';
String subject = 'Test Email with Attachment';
String body = 'This is a test email sent from Apex with an attachment!';
// Create a new email message
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Set the email properties
mail.setToList(new String[] {toAddress});
mail.setSubject(subject);
mail.setBody(body);
// Create a new attachment
Blob attachment = Blob.valueOf('Hello, World!');
mail.setAttachment(new Messaging.SingleEmailAttachment(attachment, 'text/plain', 'hello.txt'));
// Send the email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
In this example, we create a new attachment using the Blob
class and add it to the email message using the setAttachment
method. The attachment is a simple text file named hello.txt
with the contents Hello, World!
.
Example: Sending an email with a template
// Define the email properties
String toAddress = '[email protected]';
String subject = 'Test Email with Template';
String templateName = 'MyEmailTemplate';
// Create a new email message
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Set the email properties
mail.setToList(new String[] {toAddress});
mail.setSubject(subject);
// Create a new email template
EmailTemplate template = [SELECT Id, Body FROM EmailTemplate WHERE Name = :templateName].get(0);
// Set the email body using the template
mail.setBody(template.Body);
// Send the email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
In this example, we define an email template named MyEmailTemplate
and use it to set the email body. The email template is retrieved using the EmailTemplate
object and its Body
property is used to set the email body.
These are just a few examples of how you can use Apex Mail to send emails programmatically from your Salesforce code.