Setting a from address in SingleEmailMessage

I want to set a from address in a salesforce SingleEmailMessage, but can’t see a way to do this and there is no standard method described in the documentation.

I want the email to be sent from doNotReply@blahblah.com, however, the email address of the user editing the record (which triggers the email send) is used as from address.

I’m using the following code:

mail.setReplyTo(fromaddress);
mail.setSenderDisplayName(fromaddress);

But my code only changes the display name, not the email address.

Full code:

public static void sendSingleMail(id objId, ID templateId, string fromaddress) {

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setReplyTo(fromaddress);
    mail.setTemplateId(templateId);
    mail.setTargetObjectId(objId);
    mail.saveAsActivity = false;
    mail.setReplyTo(fromaddress);
    mail.setSenderDisplayName(fromaddress);

    ErrLogger.logger('Email being sent to :');
    ErrLogger.logger('objId found:  ' + objId);
    ErrLogger.logger('templateId found:  ' + templateId);
    ErrLogger.logger('fromaddress found:  ' + fromaddress);

    Messaging.sendEmail(new Messaging.SingleEmailmessage[] {mail});
}

Answer

To do this you must first set up a dedicated email address by navigating to Setup -> Administration Setup -> Email Administration -> Organization-Wide Addresses menu. Once you have created an org-wide address (note that Salesforce will require you to confirm the address prior to using it, so if you’re going to be sending things from a junk address it would be wise to set up a catch-all mailbox so you receive the confirmation email), grab the Id from the URL and use the setOrgWideEmailAddressId(Id) method on your instance of Messaging.SingleEmailMessage.

If you want to avoid hard-coding an Id, after creating your Org-Wide Address you can query them:

OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'doNotReply@blahblah.com'];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
if ( owea.size() > 0 ) {
    mail.setOrgWideEmailAddressId(owea.get(0).Id);
}

Edit: It seems someone liked my answer and added it to the KB at https://help.salesforce.com/articleView?id=000232863&type=1 – is that something Salesforce is doing now?

Attribution
Source : Link , Question Author : c14kaa , Answer Author : JCD

Leave a Comment