When sending emails programmatically in Salesforce Apex using the Messaging.SingleEmailMessage class, you may want to send emails from a shared or generic email address — such as doNotReply@domain.com — rather than from the internal Salesforce user's email address. There is no direct setFrom() method available on Messaging.SingleEmailMessage. To set a custom "from" address, an Org-Wide Email Address must first be configured and confirmed in Salesforce Setup, and then referenced in Apex using the setOrgWideEmailAddressId(Id) method.
Step 1 — Create an Org-Wide Email Address in Setup:
To set a custom "from" address on a Messaging.SingleEmailMessage instance, complete the following steps:
Navigate to Setup | Administration Setup | Email Administration | Organization-Wide Addresses and create a new entry for the desired "from" address (for example, doNotReply@domain.com). Salesforce sends a confirmation email to that address before it can be used — ensure a mailbox or catch-all is configured to receive the confirmation.
Step 2 — Use the Org-Wide Address ID in Apex:
After the address is confirmed, retrieve its ID using a SOQL query and pass it to the setOrgWideEmailAddressId(Id) method on your Messaging.SingleEmailMessage instance. This avoids hard-coding the ID directly in your code.
The following Apex code queries the confirmed Org-Wide Email Address and sets it as the "from" address on the email message. If the address is found, setOrgWideEmailAddressId() is called with the first matching record's ID:
OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'doNotReply@<somedomain>.com'];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
if ( owea.size() > 0 ) {
mail.setOrgWideEmailAddressId(owea.get(0).Id);
}000387978

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.