6

I need to be able to change thefFrom email address when I send an email from Apex code. I can do that using Org-Wide Email addresses, but the issue is that we don't want the user to use that email address when sending emails from the standard UI.

Is there any way to send an email from Apex using an org-wide email address that the profile is not allowed to send from?

1
  • a simple Custom Setting maybe? with email.setInReplyTo(MyEmailSetting.getInstance()().Org_Email_Address__c)
    – brovasi
    Dec 9, 2013 at 0:22

3 Answers 3

7

You have to Query first like this

OrgWideEmailAddress owea = new OrgWideEmailAddress();
                owea = [SELECT Id, Address, DisplayName FROM 
OrgWideEmailAddress WHERE DisplayName='[email protected]'];

and

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

if ( owea != null) {
mail.setOrgWideEmailAddressId(owea);
}
1
  • 3
    I think your code should be mail.setOrgWideEmailAddressId(owea.Id);
    – Liron C
    Aug 13, 2022 at 7:24
3

The best idea I have is pretty abstract: you can create a custom object to hold a serialized form of your email that a user has requested to send from a system-managed OrgWideEmailAddress and have a scheduled job running as an admin or otherwise privileged user that actually sends out the email, removing the message from the holding table in the process.

Quite a bit of work to build just for this, but if it's a firm requirement I don't see much in the way of better options.

2
  • Yeah, that's a lot of work. I think it is more of a nice to have. Thanks for the thoughts, though. Dec 8, 2013 at 0:11
  • That's a pretty good idea, I may try that. Alternatively, you can offload all the email-generating work into the batch job and not serialize anything. Your approach is more generic though, and can be re-used for multiple situations. May 25, 2017 at 20:53
2

Although I have not personally tested this, it would stand to reason that you should be able send the email as any address while within a trigger or a class using "without sharing".

1
  • 2
    Unfortunately, my class is marked "without sharing" and I still get the error message: "Not profiled to access this Org-wide Email Address" Dec 6, 2013 at 23:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .