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.

3 comments:

  1. Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    salesforce training in chennai | salesforce training institute in chennai

    ReplyDelete
  2. what will be the code for sending the email through apex and take the value of email through vf page

    ReplyDelete
  3. what will be the code for sending mail using apex and taking value of mail through vf page

    ReplyDelete