Mar 7, 2011

How to Send More than 10 E-mails


Hi All,


This is about how to send more than 10 E-mails. As we know we have a governor limit of sending 10 emails in a process so this is a workaround to send more than E-mails. We can do this by using batch class.


Lets say we have to send all System Administrators details of case logged by them today in a particular format. If suppose we have 15 System Administrators in our organisation, all of them logged 2-3 cases in a day and in the end of the day we want to send the details of case logged only by them in an Email. So here is the code :

global class Batch_CaseEmail implements Database.Batchable<sObject>,Database.Stateful
{
   Map<Id , List<Case>> userCaseMap {get; set;}
   List<Case> allCaseLoggedToday {get; set;}
   
   global Batch_CaseEmail()
   {
       //Map to maintain user id and cases logged by them today
       userCaseMap = new Map<Id, List<Case>>() ;
       
       //All sales rep (System admins)
       List<User> salesRep = new List<User>() ;
       salesRep = [select id , name , Email , ManagerId from User where Profile.Name = 'System Administrator'] ;
       
       //All sales rep ids
       List<Id> salesIds = new List<Id>() ;
       for(User ur : salesRep)
       {
           salesIds.add(ur.Id) ;
       }
      
       //All cases logged today by sales rep
       allCaseLoggedToday = new List<Case>() ;
       allCaseLoggedToday = [select Id, CaseNumber,CreatedById, Owner.name , account.Name , contact.name from Case where CreatedDate = TODAY AND CreatedById in : salesIds] ;
   }

   global Database.QueryLocator start(Database.BatchableContext BC)
   {
      //Creating map of user id with cases logged today by them
      for(Case c : allCaseLoggedToday)
      {
          if(userCaseMap.containsKey(c.CreatedById))
          {
              //Fetch the list of case and add the new case in it
              List<Case> tempList = userCaseMap.get(c.CreatedById) ;
              tempList.add(c);
              //Putting the refreshed case list in map
              userCaseMap.put(c.CreatedById , tempList) ;
          }
          else
          {
              //Creating a list of case and outting it in map
              userCaseMap.put(c.CreatedById , new List<Case>{c}) ;
          }
      }

      //Batch on all system admins (sales rep)
      String query = 'select id , name , Email from User where Profile.Name = \'System Administrator\'';
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<sObject> scope)
   {
       
      for(Sobject s : scope)
      {
          //Type cast sObject in user object
          User ur = (User)s ;
          
          //If system admin has logged any case today then only mail will be sent
          if(userCaseMap.containsKey(ur.Id))
          {
              //Fetching all cases logged by sys admin
              List<Case> allCasesOfSalesRep = userCaseMap.get(ur.Id) ;
              
              String body = '' ;
              //Creating tabular format for the case details
              body = BodyFormat(allCasesOfSalesRep) ;
              
              //Sending Mail
              Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage() ;
              
              //Setting user email in to address
              String[] toAddresses = new String[] {ur.Email} ;
              
              // Assign the addresses for the To and CC lists to the mail object
              mail.setToAddresses(toAddresses) ;
    
              //Email subject to be changed
              mail.setSubject('New Case Logged');
              
              //Body of email
              mail.setHtmlBody('Hi ' + ur.Name + ',<br/><br/> Details of Cases logged today is as follows : <br/><br/>' + body + '<br/> Thanks');
        
              //Sending the email
              Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
          }
      }
   }
   
   public String BodyFormat(List<Case> lst)
   {
       String str = '' ;
       for(Case cs : lst)
       {
           str += '<tr><td>'+ cs.CaseNumber +'</td>'+'<td>'+ cs.Owner.Name +'</td>'+'<td>'+ cs.Account.Name +'</td>'+'<td>'+ cs.Contact.Name +'</td>'+'</tr>' ;
       }
       str = str.replace('null' , '') ;
       String finalStr = '' ;
       finalStr = '<table border="1"> <td> CaseNumber </td> <td> Owner </td> <td> Account </td> <td> Contact </td> '+ str +'</table>' ;
       return finalStr ;
   }

   global void finish(Database.BatchableContext BC)
   {
   }

}


Now to execute this batch class we can schedule it or simply run this code in system logs for testing :

Batch_CaseEmail controller = new Batch_CaseEmail() ;
Integer batchSize = 1;
database.executebatch(controller , batchSize);



So when we execute it all system administrators will get E-mails in this format 






Thanks.

62 comments:

  1. Why not just send it to everyone at the same time e.g.

    String[] toAddresses = new String[] {'admin1@tquila.com', 'admin2@tquila.com', 'admin2@tquila.com'}

    This would then count as 1 email.

    ReplyDelete
  2. Body of each email is different and is according to the case logged in a day by each user.

    ReplyDelete
  3. Now question is what is the limit for sending emails per day. Then here it is :

    Limit for unlimited edition is 1000 email per day, professional edition is 250 and enterprise edition is 500.
    But if you are sending emails to internal users there is no limit on it.

    Here is some information I received from Salesforce on the daily email limit -

    What COUNTS towards the limit
    * Mass Emails to Contacts
    * Mass Email to Leads
    * Emails send via the API to email addresses
    * Emails send via the API to contacts (Both single and mass emails)
    * Emails send via API to Leads (both Single & Mass Emails)

    What DOES NOT COUNT towards the limit
    * Mass emails to Users
    * Emails via API to User ID’s
    * Emails send from the “Send Email” button on contacts (single emails/email author)
    * Emails send from the “Send Email” button on Leads (single emails/email author)
    * Workflow emails
    * System generated emails

    ReplyDelete
  4. Can I call the method which sends email multiple times to overcome this limitation?
    For eg: sendandAttach() is a method which sends email(content for each recipients is different). Now if I call this method multiple times will the limits still be effective?

    ReplyDelete
  5. I am not techy at all but am in the situation where I have been handed salesforce by our IT department to manage spontaenous volunteers in emergencies and natural disasters! Strange but true... We expect if this happens we will have several thousand people registered as 'customers' and will want to communicate by email with them all, but we have a 500 email limit. Do you know of any plug-ins we can use to by-pass this?

    ReplyDelete
    Replies
    1. This comment has been removed by a blog administrator.

      Delete
  6. Hey, Thanks for this nice code. I am very new to Salesforce. I want to use my templates. So please tell me how to fetch my templates and these templates are specific to the selection of radio buttons I have in a form.

    ReplyDelete
  7. Hi Ankit,

    I am working batch class but i am facing lost of issues. I am running batch class on 2 to 2.5lk records (records by query) in actual system i have 6-7lk records

    1. The query i have written in start method is taking too much time from preparing state to processing state.
    2. Some time i am getting this - "All attempts to execute message failed, message was put on dead message queue" exception.

    I have went through all salesforce docs. They suggest me to optimize query. below is my query.

    Code:

    String query = '';

    query = 'select AccountName,Id, AccountNumber, Type, Total_Balance__c from Account where Total_Balance__c !=0 and CreatedDate = LAST_N_DAYS:3' order by Id';

    System.debug('Enter into START');

    return Database.getQueryLocator(query);

    Thanks,
    Hitesh N. Patel

    ReplyDelete
  8. You wouldn't happen to have test code to go with this would you. Yep, I'm a newbie and it would be appreciated.

    ReplyDelete
  9. Thank you! The code to execute specifying a batch size is what I was missing.

    ReplyDelete
  10. Hi Ankit,

    I am facing issue with Mass Email for Leads.I have enterprise edition and trying to send Mass Email using 'Mass Email Leads' Option and limit is 500 emails but i am getting the error 'This mass email cannot be sent today as your daily limit has only 7 emails remaining. If you are going to send today go back and select 7 or fewer recipients. You may schedule this mailing for delivery at a future date.' .I don't understand the reason.
    I also tried to schedule for future date but getting error.

    Please help

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  11. Great post and Lessons, buddy. I think GetResponse is the best email marketing platform to boost your sales. Flexible, simple and cost-effective for landing page, webinar, and email automation Start your FREE trial now-@ http://bit.ly/2N7nHCX

    ReplyDelete
  12. Anyone can also use the 1st mass mailer software for directkly send maximum email in one click.

    ReplyDelete
  13. This Article explain what's the process email Marketing and how it enhance sale. Thank you for sharing these wonderful tips. It’s like a collecting of lots of email account including personal information. hope you keep sharing such kind of information Bulk Mailer Software

    ReplyDelete
  14. Such an amazing blog.
    mass mailer software csn help you send bulk emails.

    ReplyDelete
  15. Avro keyboard free download for Windows Ubuntu,
    Linux and MacOS operating system with full offline installer supports both 32-bit and 64-bit operation system.
    Download Bang



    Free download full version of bijoy ekattor 71 for windows with free activation process and installation process.
    User friendly interface, easiest typing system, lots of typing automation tool,
    free online support makes it the most popular Bangla typing software of today.



    Bijoy Bayanno 2018 full latest version free download for Windows Xp/7/8/10.
    This is a full latest version of Bijoy 52 with full activation serial key you can download from here.bijoy bangla keyboard




    Free download bijoy keyboard full version with 100% working serial key for Windows Xp, Windows 7,
    Windows 8, Windows 10 supports both 32-bit and 64-bit windows version. bijoy bayanno free download is the best Bangla Typing software


    bijoy bayanno free download




    download pc software for free

    ReplyDelete
  16. IPL Season 12 Schedule – Complete Details for Indian Premier League 2019 Dates, Time, Venues, Teams & Fixtures
    IPL 2019 Schedule

    ReplyDelete
  17. How to put 600000 records into one single file and that file send through email

    ReplyDelete
  18. Hey Nice Blog!!! Thank you for sharing information. Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!!!

    Bulk Email Service Providers in Lucknow
    Bulk Sms Provider in Lucknow
    Best SEO Company in Munshipuliya,Lucknow
    Best SEO Expert in Lucknow

    ReplyDelete
  19. Thanks for sharing such a nice blog. Web email grabber help you to grab the genuine list of emails from websites email extractor

    ReplyDelete
  20. Good content and nice blog. Thanks for sharing

    such great information. hope you keep sharing such

    kind of information Advance Bulk Mailer

    ReplyDelete
  21. Such a great blog ! Thanks for sharing this informative with us ! Good Content!
    Bulk Email Software

    ReplyDelete
  22. This post is absolutely great because I also would like to start using various bulk email as well as SMS marketing techniques in order to grow the sales for the home based business. We currently serve in the local area only would like to get an affordable app to bulk Send sms from slack.

    ReplyDelete
  23. what an amazing way to explain your ideas. I am impressed with your writing skill. I am really glad to read this one. n this article you really explain the topic very well. thank you so much for this one. keep sharing your ideas and thoughts. Know more about ICO Development connect with us.

    ReplyDelete
  24. this is something that i have been searching for a long time! at last you have ended my painful research thank you for that digital marketing agency

    ReplyDelete
  25. You can use 1st mass mailer software for directkly send maximum email in one click.

    ReplyDelete
  26. Sometime few such blogs become very helpful while getting relevant and new information related to your targeted area. As I found this blog and appreciate the information delivered to my database.

    Php projects with source code
    Online examination system in php
    Student management system in php
    Php projects for students
    Free source code for academic
    Academic project download
    Academic project free download

    ReplyDelete
  27. Seo company in Varanasi, India : Best SEO Companies in Varanasi, India: Hire Kashi Digital Agency, best SEO Agency in varanasi, india, who Can Boost Your SEO Ranking, guaranteed SEO Services; Free SEO Analysis.

    Best Website Designing company in Varanasi, India : Web Design Companies in varanasi We design amazing website designing, development and maintenance services running from start-ups to the huge players


    Wordpress Development Company Varanasi, India : Wordpress development Company In varanasi, india: Kashi Digital Agency is one of the Best wordpress developer companies in varanasi, india. Ranked among the Top website designing agencies in varanasi, india. wordpress website designing Company.

    E-commerce Website designing company varanasi, India : Ecommerce website designing company in Varanasi, India: Kashi Digital Agency is one of the Best Shopping Ecommerce website designing agency in Varanasi, India, which provides you the right services.

    ReplyDelete
  28. Nice blog I like to read your blog please keep it up.Website Design and Development are two different processes that get combined so that someone who visits a website gets a good user experience. Design is important and implementing that design in a right manner is development. Arkss Technologies is a Website Design & Development Company In USA having separate teams of Developers and Designers who work closely to design and develop your dream website.

    ReplyDelete
  29. Nice blog I like to read your blog please keep it up.Website Design and Development are two different processes that get combined so that someone who visits a website gets a good user experience. Design is important and implementing that design in a right manner is development. Arkss Technologies is a Website Design & Development Company In USA having separate teams of Developers and Designers who work closely to design and develop your dream website.

    ReplyDelete
  30. If you're looking any type of advertising services whether it's online or offline, Sigma Trade Wings is the right option for you.
    :
    𝐅𝐨𝐫 𝐦𝐨𝐫𝐞 𝐝𝐞𝐭𝐚𝐢𝐥𝐬 𝐜𝐨𝐧𝐭𝐚𝐜𝐭 𝐮𝐬
    𝐚𝐭 http://stw.co.in/
    📱 7521888222

    ReplyDelete
  31. Only one first impression grant to you, so make it a good one. While preparing for a property appraisal, you are strongly encouraged to make an entire journey from home. You have to be critical and look at it from an unselfish person's perspective as you go around your home.

    ReplyDelete
  32. Web Development Company in Lucknow to build responsive websites
    Web development company in Lucknow which helps you with your biggest interest that is responsive website is none other than Highflyseo. From national to international clients, they have around 600+ happy clients which have received the results they wanted from this company. Apart from the web development they also provide you the optimization you need to grow and reach to the top page of Google. Highflyseo is the best web development company in Lucknow not only because of their responsive websites but because of their service quality. Being new they help with every problem whether the project is big or small and that is one of the biggest disadvantages of using such services from these types of companies whose main motive is to provide the best to their clients.
    If you need custom coded website or just a basic wordPress website, they have an experienced and skilled team for that which have created a lot of websites, and have the algorithms of how a website should be to rank higher which could give you better business, and that is why this company is called as one of the best web development company in Lucknow.

    Best Web development company in Lucknow | How they help you boost your Page Score through web development?
    Creating a website is not enough; it has to be responsive, attractive and best of all it should have a 100% SEO score which helps your website to rank at the top and compete with other websites. They use their skills to create websites with such scores which automatically brings the best out of the website and makes your website a lot better from the start, after that their main focus is to make the website responsive because people likes a websites in their first initials 5 seconds and if the website didn’t respond fast people will leave your website eventually. So they are the best web development company in Lucknow for that for sure.
    There are many companies for such services so we decided to compare the prices, service quality, and came to know that they are the best web development company in Lucknow.

    Besides Web Development what other services could you expect from Highflyseo?
    These services are sufficient for you create a website and rank it up to the top.
    • Pay Per Click
    • Social Media
    • Technical SEO Audit
    • Content Marketing

    So should you hire them?
    We definitely suggest you to hire them for your website creation; Highflyseo is the best web development company in Lucknow in terms of prices, service quality, overall everything. You shouldn’t think twice before giving them a chance to prove themselves. We have analyzed the results and finally came to this conclusion that their web development service is best in Lucknow. Not their national but international customers are very satisfied with their services..
    They are the best web development company in Lucknow, what are you waiting for contact them or have a meet with them. Contact details are below.
    Address: Shanti Nagar, Sarojini Nagar, Lucknow 226008
    Email: info.highflyseo@gmail.com
    Phone: +91-6387139674
    Fax: +91-9519155311



    ReplyDelete
  33. I did go through the article and would appreciate the efforts of the writer to share such an insightful and well-researched article. keep doing it

    Top CRM Software

    ReplyDelete
  34. To identify the best email marketing software for different businesses, If you need
    email marketing software that’s easy to use, affordable, and will turn your leads into customers. More than your requirement you can send bulk emails as well to your target customers.

    ReplyDelete
  35. This could be a problem with my internet browser because I’ve had this happen before. Thank you

    야동
    대딸방
    스포츠마사지
    출장마사지
    바카라사이트

    ReplyDelete
  36. I really enjoyed reading your blog. It was very well written and easy to understand. Unlike other blogs that I have read which are actually not very good. Thank you so much! FDM is one of the
    Best Email Marketing Company Services in Chennai.
    . For More Details Contact us: 91+ 9791811111 or visit our website.

    ReplyDelete
  37. First of all, thank you for your post. majorsite Your posts are neatly organized with the information I want, so there are plenty of resources to reference. I bookmark this site and will find your posts frequently in the future. Thanks again ^^

    ReplyDelete
  38. What if I don't want to use For loop is there any other option or Do you have SMTP Explained blog or post

    ReplyDelete
  39. Fdm is the best web design coimbatore.We create digital marketing campaigns that go beyond the screen and deliver high results . Make an enquiry now +91 9791811111 Or check out our website : https://www.fueldigi.com/coimbatore/



    ReplyDelete
  40. Thank you for sharing such great information. Get the more details to know about the FuelDigi Marketing Pvt Ltd is one of the Best sem services chennai. We provide the best digital solutions, SEO, SEM and Social Media Marketing services.etc CONTACT US :+91 9791811111 learn more : https://www.fueldigi.com/

    ReplyDelete
  41. Fueldigi Marketing Pvt Ltd is the best graphic design company in coimbatore Since utmost of the people does online shopping currently, digital marketing is indeed the good strategy for you to find your ideal customers in the online platforms.for more info +91 9791811111 Or check out our website : https://www.fueldigi.com/coimbatore/

    ReplyDelete
  42. Fueldigi Marketing Pvt Ltd is the Best branding company in coimbatore we work to turn our clients' dreams into reality call now 9791811111 or see our website : https://www.fueldigi.com/coimbatore/

    ReplyDelete
  43. Fueldigi Marketing Pvt Ltd is the Best coimbatore logo designers We set the strategy for writing content and designing ads. Count on us as your complete online marketing partner.Call Now : 9791811111 Visit Our Website : https://www.fueldigi.com/coimbatore/

    ReplyDelete
  44. Fueldigi Marketing Pvt Ltd is the Best logo creator in coimbatore brings together under one roof all the services that can make your business be born (read developed), spruce up (read designed), taught and informed (read advanced) to have a prospering life ahead (read achievement and profit) for more info +91 9791811111 Or check out our website : https://www.fueldigi.com/coimbatore/

    ReplyDelete
  45. Fueldigi Marketing Pvt Ltd offer a Top advertising company in coimbatore Our digital media agency will merge key tools & techniques to give birth to a unique solution which is fundamental for take your business higher than ever.. Make a query today +91 9791811111 or Vist Our Website : https://www.fueldigi.com/coimbatore/

    ReplyDelete
  46. Fueldigi Marketing is the Top web developers in coimbatore we convert your audience into leads and initiate profits, Increased visibility, marketing opportunity at efficient budgets. For more details Contact us: +91 9791811111 or Visit our website https://www.fueldigi.com/coimbatore/

    ReplyDelete
  47. Fueldigi Marketing Pvt Ltd is Providing best digital marketing services in coimbatore. Our teams provide dedicated services to our clients with creative techniques and methods to ensure their satisfaction of business growth. For More Info : 9791811111 or For Online enquiry : https://www.fueldigi.com/coimbatore/

    ReplyDelete