63

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});
}

1 Answer 1

70

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?

1
  • I found the KB and didn't know who came first! Good for you! Jul 25, 2018 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.