SEND EMAILS USING APEX

Email Methods

The following are methods for Email. All are instance methods.

1. SINGLE EMAIL

public class Messagingdemo {

    public static void sendSingleMessage(){
       
        Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
       
        // Strings to hold the email addresses to which you are sending the email.
        String[] toAdd=new String[]{'ankikadam@gmail.com'};
        String[] ccAdd=new String[]{'ankitakadamrocks@gmail.com'};
       
      // Assign the addresses for the To and CC lists to the mail object.
      mail.setToAddresses(toAdd);
      mail.setCcAddresses(ccAdd);
     
        // Specify the address used when the recipients reply to the email.
      mail.setReplyTo('ankikadam98@gmail.com');
       
        // Specify the name used as the display name.
      mail.setSenderDisplayName('Ankita');

      // Specify the subject line for your email address.
      mail.setSubject('Welcome to salesforce!!!!!');
       
        // Specify the text content of the email.
      mail.setPlainTextBody('Your ORG is setup');
       
       
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
       
       
       
       
    } }






2. MASS EMAIL

MassEmailMessage Class


MassEmailMessage Constructors

The following are constructors for MassEmailMessage.


public class Messagingdemo {

  public static void sendMassEmails(){
       
       
        EmailTemplate et = [SELECT Id,Subject, Body FROM EmailTemplate WHERE Name ='ApexEmailTemplateMessage'];
        List<Contact> contacts=[Select Id,Email From Contact Where LastName='Eze'];
        List<Id> conIds=new List<Id>();
        List<Id> whatIds=new List<Id>();
        for(Contact c: contacts) {
            conIds.add(c.Id);
            whatIds.add(et.Id);
        }

        Messaging.MassEmailMessage email = new Messaging.MassEmailMessage();
        email.setTargetObjectIds(conIds);
        email.setTemplateId(et.id);
        Messaging.SendEmail(New Messaging.MassEmailMessage[] {email});

       
  }
}




LIMITS ON SENDING EMAILS IN APEX
  • Max total of 5000 single emails to external addresses per day
  • Max total of 5000 mass emails to external addresses per day
  • Max total of 150 email recipients specified in the tocc, and bcc fields
  • Max size of 4,000 bytes for the tocc, and bcc fields

Note: Each email sent to a duplicate email address counts as an individual email.

In case you exceed any of the mentioned limits, Salesforce will stop your code from running and provide you with either of the following errors: SINGLE_EMAIL_LIMIT_EXCEEDED or MASS_MAIL_LIMIT_EXCEEDED.

To prevent your code from sending any emails past a certain limit and thus avoid facing errors, the following method can be used Messaging.reserveMassEmailCapacity(50); with the number in the brackets indicating the max number of emails.




Comments