Use an Email Service Address as Organization Wide Address

March 3, 2018

Whenever you add an email address as an Organization Wide Address, Salesforce sends a verification email to that address with a link you have to click to verify that it is a real and valid address. Since the email service address you create doesn't have an inbox where you can open and click the verification link sent, you will have to leverage the Inbound Email Handler Apex class which can process all the mails sent to it (including the verification email).

Add the below code to your Inbound Email Handler, which creates a Document with the Name "Organization-Wide Address Verification" in the folder of your choice whenever the verification email gets sent to the service address. You can then open the document (which is a HTML document) and click the Verification Link to verify the address.

if(String.isNotBlank(email.subject) && email.subject.containsIgnoreCase('Verify your Salesforce Organization-Wide Address')){

List<Document> documents;
if(Document.sObjectType.getDescribe().isAccessible()){
documents = [select id from Document where Name = 'Organization-Wide Address Verification' limit 1];
}
Document d = documents.isEmpty() ? new Document() : documents[0];
d.body = Blob.valueOf(email.htmlBody);
d.Name = 'Organization-Wide Address Verification';
d.ContentType = 'text/html';
d.Type = 'html';
d.FolderId = [select id from Folder where name = 'Shared Documents' and Type='Document' limit 1].id; //You can choose any Document Folder you want
if(Document.sObjectType.getDescribe().isCreateable() && Document.sObjectType.getDescribe().isUpdateable()){
upsert d;
}

}