Sunday 4 August 2013

How to send Email from Apex code with controlling 'From Address' & Sender's Name Dynamically

Hi friends,

Today I came up with one interesting thing to share with you. Generally we send emails from Salesforce using following ways :-
1. Apex Code
2. Email Alerts
3. Outbound messaging etc.

In all of these ways we normally set 'To'/'Cc'/'Bcc' but have you thought how to control 'From address of email'? what to do if we need to send email displaying any other email address in 'from' part instead of sender's email address. Here is one Salesforce feature to get rid of this problem that is "Organization-Wide Email Addresses".


In above screen shot you just need to
1. Navigate Setup -> Email Administration ->  Organization-Wide Email Addresses
2. Click on Add button.
3. Enter email Id and display name of sender.
4. In order to complete this process you need to get verified email id you are putting here ( in this example it is 'testuser@gmail.com').

Now it is ready for use. Let's see how we can use it in Apex code side:-

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
string body = 'Hi ';
String[] toAddresses = new String[] {'sksworld10@gmail.com'}; 
mail.setToAddresses(toAddresses);
mail.setSubject('Test Subject');  
mail.setSaveAsActivity(false);  
for(OrgWideEmailAddress owa : [select id, Address, DisplayName from OrgWideEmailAddress]) 
{
 if(owa.Address.contains('testuser')) 
  mail.setOrgWideEmailAddressId(owa.id); 
}
mail.setHtmlBody(body);  
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


Here you can notice that we can control 'From address' in sending email.

Thanks for reading this article.

No comments:

Post a Comment