Sunday 24 March 2013

Send an email from Apex using Messaging.sendEmail

Apex provides us the oppurtunity to send an email from controller/trigger. There are few situation where you cannot send an email via workflow because of any reason, then you use below code to achieve this.

Apex Code:

  • For sending an email without using email template:
    private void sendMailToUser()
    {
         string messageBody = 'Hi abc,\n\n This is the test email body' +  '\n\n Thanks';
       
         Messaging.SingleEmailMessage objMail = new Messaging.SingleEmailMessage();
         String[] toAddress = new String[]{};
         toAddress.add('test@test.com'); // Adding recipient address in a list
         objMail.setToAddresses(toAddress); // setting to address in the email
         objMail.setReplyTo('donotreply@test.com');
         objMail.setSenderDisplayName('Administrator');
         objMail.setSubject(Test Subject');
         objMail.setPlainTextBody(messageBody); //adding message body
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { objMail }); // sending an email
    }

  • For sending an email using email template to a single user:
     public void SendEmail()
    {
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
         mail.setTargetObjectId(con.Id); // id of the contact, lead, or User
         mail.setTemplateId('00***********XU'); // Id of the email template

         mail.setSaveAsActivity(false);
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

  • To send mass email to a group of users:
     public void SendEmail()
    {
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
         mail.setTargetObjectIds(conList); // List of  ids of the contact, lead, or User
         mail.setTemplateId('00***********XU'); // Id of the email template

         mail.setSaveAsActivity(false);
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }



Template Id:
You can use SOQL query to fetch the id of the particular email template.
Syntax:
EmailTemplate e : [select Id,Name,Subject,body from EmailTemplate where name = 'abcd'];

No comments:

Post a Comment