In Salesforce, you can set the “From” address in a SingleEmailMessage by using the setOrgWideEmailAddressId method. Here’s an example of how you can set the “From” address:
// Create a new instance of SingleEmailMessage
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Set the "From" address using the Organization-Wide Email Address ID
String orgWideEmailAddrId = '[OrgWideEmailAddressId]'; // Replace with the actual Organization-Wide Email Address ID
email.setOrgWideEmailAddressId(orgWideEmailAddrId);
// Set other email properties such as recipients, subject, and body
email.setToAddresses(new List<String>{'recipient@example.com'});
email.setSubject('Sample Email');
email.setPlainTextBody('This is a sample email.');
// Send the email
Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
Make sure to replace [OrgWideEmailAddressId] with the actual Organization-Wide Email Address ID that you want to use as the “From” address. The Organization-Wide Email Address must be previously defined in Salesforce setup.
By setting the “From” address using the Organization-Wide Email Address ID, you can specify the desired email address to appear as the sender for the SingleEmailMessage.
TIPS
If you don’t have any org-wide address then follow below steps to create one:
- Log in to your Salesforce org as a user with administrative privileges.
- Navigate to Setup by clicking on the gear icon in the top-right corner and selecting “Setup” from the dropdown menu.
- In the Quick Find search bar on the left-hand side, type “Organization-Wide Addresses” and select the corresponding option under the Email section.
- Click on the “New Organization-Wide Address” button.
- Enter the required information for the Organization-Wide Email Address:
- Email Address: Provide the email address you want to use as the “From” address.
- Display Name: Optionally, enter a display name that will be shown to recipients.
- Salesforce User: Choose the Salesforce user associated with the email address.
- Click “Save” to create the Organization-Wide Email Address.
