About

Edit photo

Thursday, February 9, 2017

send email in apex salesforce


Salesforce provides method to send emails from apex. We can create a instance of that method, set all the required parameters and then send the emails.

We can set the email addresses to which the email be sent in "setToAddresses", we can give emails seperated by comma. Simialrly bcc,cc email addresses can be seperated by comma . We can specify the body as text or HTMl as desired.

Following is a example wherein emails will be sent to specified addresses upon clicking the button.

Visualforce page <apex:page controller="SendemailController">
 <apex:form >
   <apex:commandButton value="Send Email" action="{!sendEmailFunction}"/>
 </apex:form>
</apex:page>


Controller 
Public with sharing class SendemailController{
   Public SendemailController(){
   }
  
 Public void sendEmailFunction(){
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String[] toAddresses = new String[] {'testreceipient1@mail.com','testreceipient1@mail.com'}; 
   String[] ccAddresses = new String[] {'testcc1@mail.com','testcc1@mail.com'};
   mail.setToAddresses(toAddresses);
   mail.setCcAddresses(ccAddresses);
   mail.setReplyTo('myemail@mail.com');
   mail.setSenderDisplayName('My Name');
   mail.setSubject('Testing email through apex');
   mail.setBccSender(false);
   mail.setUseSignature(false);
   mail.setPlainTextBody('This is test email body. This mail is being sent from apex code');
   //mail.setHtmlBody('<b> This is HTML body </b>' );
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 } 

}

You need to specify the existing correct addresses in the lines marked red in abive code.

0 comments:

Post a Comment