Saturday, June 18, 2011

How to send mass emails to users in salesforce


Recently I was working on a requirement where I created multiple portal users in a single process. Now I need to sent them an email with different body. I would like to share the approach which I used.

In the below sample code I am iterating over a list of partner users ("lstPortalUser"). This list is created by me as per my requirement. You can create same list as per your requirement.

List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for(User portalUser :lstPortalUser)
{   
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   string body = 'Hi '+ portalUser.LastName;  
   mail.setSubject('Test Subject');
   mail.setTargetObjectId(portalUser.Id);
   mail.setSaveAsActivity(false);
   mail.setHtmlBody(body);
   mails.add(mail);
}
Messaging.sendEmail(mails);

Please let me know if there is any issue.
Thanks,

10 comments:

  1. Hi Dev,
    I have posted some issues regarding the same here

    ReplyDelete
  2. How many mail can be added to list [ mails.add(mail) ] ?? Is there any limitation??

    ReplyDelete
  3. Please refer the following link for more details.
    http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_single.htm

    ReplyDelete
  4. I have read this doc and others before. But none of them answered my questions - how many mail(SingleEmailMessage object) can be added to List?

    ReplyDelete
  5. There is no limit on to add SingleEmailMessage in List.
    There is a limit on toAddress field. You can add upto 100 email address at a time.
    In a single process you can call sendEmail method 10 times only.

    ReplyDelete
  6. Hey Dev, Thanks for sharing with us. I have not tried to send emails in mass i will try now..

    Thanks
    Sathish

    ReplyDelete
  7. Thanks a bunch for sharing this with all people you actually recognize what you are talking about! Bookmarked. Kindly also discuss with my website.
    B2B Email List

    ReplyDelete
  8. hey Devendra,
    you said 'Now I need to sent them an email with different body.'
    but you given a same body 'string body = 'Hi '+ portalUser.LastName; mail.setHtmlBody(body); mail.setHtmlBody(body); ' u r sending the same body to different peoples.

    ReplyDelete
  9. can a mass email be sent to external email address other than contacts, leads, users. if possible, could you please show me how??

    ReplyDelete
  10. thanks for the very useful post...

    ReplyDelete