Loading

Setting a 'from' address in SingleEmailMessage

Data pubblicazione: Apr 24, 2026
Descrizione

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.

Risoluzione

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);
}
Numero articolo Knowledge

000387978

 
Caricamento
Salesforce Help | Article