+ Start a Discussion
SFDC@ErrorSFDC@Error 

Send Email using Vf page

Hi All,
How can i send an email with default email template using visual force page? 
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Visualforce:
<apex:page controller="emailSending">
    <p>
        Test Email Sending:
    </p>
    <apex:form>
        <apex:outputLabel value="Send Mail To: " for="To"/>
        <apex:inputText value="{!toMail}" id="To"/><br/>
        <apex:outputLabel value="CC Mail To: " for="CC"/>
        <apex:inputText value="{!ccMail}" id="CC"/><br/>
        <apex:outputLabel value="Reply Mail To: " for="rep"/>
        <apex:inputText value="{!repMail}" id="rep"/><br/>
        <apex:commandButton action="{!sendMail}" value="Send Email"/>
    </apex:form>
</apex:page>

Controller:
public class emailSending {
    public string toMail { get; set;}
    public string ccMail { get; set;}
    public string repMail { get; set;}
     
    public void sendMail(){
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        string[] to = new string[] {toMail};
        string[] cc = new string[] {ccMail};
         
        email.setToAddresses(to);
        if(ccMail!=null && ccMail != '')
            email.setCcAddresses(cc);
        if(repmail!=null && repmail!= '')
            email.setInReplyTo(repMail);
         
        email.setSubject('Test Mail');
         
        email.setHtmlBody('Hello, <br/><br/>This is the test mail that you generated. <br/>The Email Id for which this mail was generated by '+toMail+'<br/><br/>Regards<br/> Developer');
        try{
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        }catch(exception e){
            apexpages.addmessage(new apexpages.message(apexpages.severity.error,e.getMessage()));
        }
         
        toMail = '';
        ccMail = '';
        repMail = '';
    }
}

Please refer to the below links which might help you further with the above requirement.

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_email_custom_controller.htm

https://help.salesforce.com/articleView?id=000181102&language=en_US&type=1

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
SFDC@ErrorSFDC@Error
Yes Anas correct.but i want to use visual force Email Template.
Khan AnasKhan Anas (Salesforce Developers) 
Try this:
public void sendMailVf () {
        List<User> lstcon=[SELECT id FROM User WHERE Email='test@gmail.com' LIMIT 1];
        String contid;
        for(User c:lstcon) {
            contid = c.Id;
        }      
        EmailTemplate et=[SELECT Id FROM EmailTemplate WHERE developername = 'Visualforce_Template' LIMIT 1];
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(contid);
        mail.setTemplateId(et.id);
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setSenderDisplayName('Salesforce');
        mail.setSaveAsActivity(false); 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

Regards,
Khan Anas
SFDC@ErrorSFDC@Error
Hi Anas, I have developed this controller,but need to display template details in the body by default, that is not working
<apex:page lightningStylesheets="true" standardController="Contact" extensions="ClsSendEmailByTemplate1">
<apex:form >
    <apex:pageMessages ></apex:pageMessages>
    <apex:pageBlock title="Email" id="PB">
        <apex:pageBlockSection columns="1">
            <apex:pageBlockSectionItem >
                <apex:outputLabel value="Contact"/>
                <apex:inputField value="{!usr.Email}" required="true"/>
            </apex:pageBlockSectionItem>
               
            <apex:pageBlockSectionItem >
                <apex:outputLabel value="Subject" />
                <apex:outputField value="{!ET.Subject}" style="width: 500px;"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel value="Body" />
                <apex:inputTextarea style="height:300px; width:1020px" value="{!ET.Body}"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel />
                <apex:commandButton value="Send" action="{!sendMail}"/>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>      
    </apex:pageBlock>
    
    
</apex:form>

</apex:page>
 
public class ClsSendEmailByTemplate1{

    public ClsSendEmailByTemplate1(ApexPages.StandardController controller) {
             this.usr=[select id,Email from contact where id=:'0032800001Damo6'];
    }

    public string EmailTempateId{get;set;}
    public EmailTemplate ET{get;set;}
    public string emailVal{get;set;}
    public string cc{get;set;}
    public string emailSubject{get;set;}
    public string body{get;set;}
    public Contact usr{get;set;}
  
   
    
    
  
 
    public void getTemplate(){
        try{
            if(EmailTempateId == null || EmailTempateId == ''){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please Select Email Template'));
            }
            else{
                ET = [Select Id,Subject,Body from EmailTemplate where developername = 'SupportCaseAssignmentNotification' LIMIT 1];
            }
        }
        catch(Exception ex){
             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,ex.getMessage()));
        }
    }
        
     public void sendMail( ){
        try{ 
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
            email.setTemplateId(ET.Id); 
             List<String> sendTo = new List<String>();
             sendTo.add(usr.Email);
            email.setToAddresses(sendTo);   
           
            Messaging.SendEmailResult[] sendResult;
            
            Messaging.SendEmailResult [] r =Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Email Has Been Sent');
            ApexPages.addMessage(myMsg);
        }
        catch(Exception ex){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,ex.getMessage()));
        }
    }
}