+ Start a Discussion
Jobelle Belgar 14Jobelle Belgar 14 

Create a Trigger or Class that will auto-populate "Additional to" email address field in EmailMessage object

Hi All,

I have just began practicing salesforce development and would like to ask for your help. I have a custom object Circuit__c and I create a custom button overriden by a visualforce page that leads to Send Email page with specific Email template and field values. I have to set different values on "Additional to" email field based on the value in a custom picklist or lookup field on the Circuit object. I'm not sure if I should use trigger or add some codes on my class. Here is the sample code:
 
public with sharing class emailHelper {
  // In a separate class so that it can be used elsewhere
public Circuit__c ckt {get;set;}    
public User myUser { get;set;}

public emailHelper(ApexPages.StandardController stdController)
{ ckt = (Circuit__c)stdController.getRecord(); 
}

User currentUser = [Select email from User where username = :UserInfo.getUserName() limit 1];  

public  PageReference sendEmail() {
PageReference emailPage = new PageReference('/email/author/emailauthor.jsp');
Map<String, String> params = emailPage.getParameters();
params.put('p3_lkid',ckt.ID); //email will be attached to the activity history of the account where the button was clicked using the ckt.ID
params.put('template_id','00X7F000001GKu8'); /// template ID of the email template to be shown goes here
params.put('rtype','003');
params.put('p24','belgarjobelle@gmail.com; sample@dummy.org; blabla@email.com'); //currentUser.Email showing in "Additional to" field
params.put('p5','support@intelletrace.com'); //email address showing in Bcc field
params.put('new_template','1'); 
params.put('retURL',ApexPages.currentPage().getUrl()); //after send button is clicked, go back to the account where the button was clicked
     
return emailPage;
  
    }  
}

Thanks for your help!
Best Answer chosen by Jobelle Belgar 14
Varun SinghVarun Singh
Hi @ jobelle

Just update your Controller with Constructor(pass  ApexPages.StandardController controller )
public with sharing class ComposeMail {

    public Attachment attach { get; set; }

    public String text1 { get; set; }

    public String subject1 { get; set; }

    public String toaddre { get; set; }

    String tmpID = 'a067F000000dOULQA2';
    Circuit__c c=[Select id,Vendor_type__c from circuit__c where id=:tmpID];
    
    public ComposeMail (ApexPages.StandardController controller){
    if(c!=null){
    
    if(c.Vendor_type__c=='moon')   {
    toaddre ='moon@gmail.com';
    }
    if(c.Vendor_type__c=='space')   {
    toaddre ='space@gmail.com';
    }
    if(c.Vendor_type__c=='stars')   {
    toaddre ='stars@gmail.com';
    }   
    }

    attach=new attachment();
    
     }
   
    public PageReference sendmai() {
        list<Messaging.singleEmailMessage> mails=new list<Messaging.SingleEmailMessage>();
    Messaging.singleEmailMessage mail=new Messaging.SingleEmailMessage();
    list<String> toadd=new List<String>();
    for(string eachemail:toaddre.split(','))
    {
    toadd.add(eachemail);
    }
   //file attachment
     list<Messaging.EmailFileAttachment> lstefa = new list<Messaging.EmailFileAttachment>();
   
    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
    
    efa.setfilename(attach.name);
    efa.setinline(true);
    efa.setbody(attach.body);
    lstefa.add(efa);
    mail.setfileattachments(lstefa);
    mail.setToAddresses(toadd);
    system.debug(toadd);
    mail.setSubject(subject1);
    mail.setTemplateId('Your Email Template Id');
EmailTemplate objEmailTemplate=[select id, name from EmailTemplate where Name='Birthday Emailer'];
    mail.setPlainTextBody(text1);
    mails.add(mail);
   messaging.sendEmail(mails);
    
        return null;
    }

}

 

All Answers

Varun SinghVarun Singh
Hi  Jobble,
You can add set to address and CCtoAddress


// Step 0: Create a master list to hold the emails we'll send

  List<Messaging.SingleEmailMessage> mails = 
  new List<Messaging.SingleEmailMessage>();
  

      // Step 1: Create a new Email
      Messaging.SingleEmailMessage mail = 
      new Messaging.SingleEmailMessage();
    
      // Step 2: Set list of people who should get the email
      List<String> sendTo = new List<String>();
      sendTo.add(myContact.Email);
      mail.setToAddresses(sendTo);
    
      // Step 3: Set who the email is sent from
      mail.setReplyTo('sirdavid@bankofnigeria.com');
      mail.setSenderDisplayName('Official Bank of Nigeria');
    
      // (Optional) Set list of people who should be CC'ed
      List<String> ccTo = new List<String>();
      ccTo.add('business@bankofnigeria.com');
      mail.setCcAddresses(ccTo);

      // Step 4. Set email contents - you can use variables!
      mail.setSubject('URGENT BUSINESS PROPOSAL');
      String body = 'Dear ' + myContact.FirstName + ', ';
      body += 'I confess this will come as a surprise to you.';
      body += 'I am John Alliston CEO of the Bank of Nigeria.';
      body += 'I write to request your cooperation in this ';
      body += 'urgent matter as I need a foreign partner ';
      body += 'in the assistance of transferring $47,110,000 ';
      body += 'to a US bank account. Please respond with ';
      body += 'your bank account # so I may deposit these funds.';
      mail.setHtmlBody(body);
    
      // Step 5. Add your email to the master list
      mails.add(mail);

  // Step 6: Send all emails in the master list
  Messaging.sendEmail(mails);

Here are a few things to keep in mind before sending emails with Apex:
There are limits to the number of emails you can send per day.
If you can create the email alert using workflows instead of code, always do it with workflows!
It’s sometimes helpful to send emails only when a field changes to a certain value.
Sending an email with Apex is easy because you always follow the same template:
Jobelle Belgar 14Jobelle Belgar 14
Thanks for the response, Varun. I understand that I can auto-populate the fields. But in my situation, I need different values for the fields which is dependent to a custom field. For example, I have a Circuit object with custom picklist field (Vendor_type__c) with values:

Space
Moon
Stars

When I create an email under one circuit record, I would like to pre-define the values for the "Additional to" email address field depending on the picklist value of the circuit record. If the circuit has the 'Space' value, the email address should contain "space@example.com", same goes with other values:

'Moon'=moon@example.com
'Stars'=stars@example.com

How should I do it? I have already figured out how to auto-populate the fields but I don't know how to set the criteria.
 
Varun SinghVarun Singh
Hi @jobelle

I have updated  your controller and  try in my vf page .It is working fine i have  put here hardcoded id you have to use ckt.id there
I hope you can understand How to select diifferent address according to diff  picklist.

Controller
 
public with sharing class ComposeMail {


    public Attachment attach { get; set; }

    public String text1 { get; set; }

    public String subject1 { get; set; }

    public String toaddre { get; set; }

    String tmpID = 'a067F000000dOULQA2';
    Circuit__c c=[Select id,Vendor_type__c from circuit__c where id=:tmpID];
    
    public ComposeMail (){
    if(c!=null){
    
    if(c.Vendor_type__c=='moon')   {
    toaddre ='moon@gmail.com';
    }
    if(c.Vendor_type__c=='space')   {
    toaddre ='space@gmail.com';
    }
    if(c.Vendor_type__c=='stars')   {
    toaddre ='stars@gmail.com';
    }   
    }

    attach=new attachment();
    
     }
   
    public PageReference sendmai() {
        list<Messaging.singleEmailMessage> mails=new list<Messaging.SingleEmailMessage>();
    Messaging.singleEmailMessage mail=new Messaging.SingleEmailMessage();
    list<String> toadd=new List<String>();
    for(string eachemail:toaddre.split(','))
    {
    toadd.add(eachemail);
    }
   //file attachment
     list<Messaging.EmailFileAttachment> lstefa = new list<Messaging.EmailFileAttachment>();
   
    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
    
    efa.setfilename(attach.name);
    efa.setinline(true);
    efa.setbody(attach.body);
    lstefa.add(efa);
    mail.setfileattachments(lstefa);
    mail.setToAddresses(toadd);
    system.debug(toadd);
    mail.setSubject(subject1);
    mail.setPlainTextBody(text1);
    mails.add(mail);
   messaging.sendEmail(mails);
    
        return null;
    }

}

VF page
 
<apex:page controller="ComposeMail">
  <apex:form >
 <style>
 .fileType {
    display: block;
    position: relative;
    width: 200px;
    margin: auto;
    cursor: pointer;
    border: 0;
    height: 60px;
    border-radius: 5px;
    outline: 0;
}
.fileType:hover:after {
    background: #FF1111;
}
.fileType:after {
    transition: 200ms all ease;
    border-bottom: 3px solid rgba(0,0,0,.2);
    background: #000000;
    background-image:url('http://i.stack.imgur.com/CVpp3.jpg');
    text-shadow: 0 2px 0 rgba(0,0,0,.2);
    color: #fff;
    font-size: 20px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    content: 'Upload Something';
    line-height: 60px;
    border-radius: 5px;
    }
 </style>
  <apex:pageBlock >
 <apex:pageBlockSection >
  
  <apex:pageBlockSectionItem >
   To Addresses<apex:inputText value="{!toaddre}"/>
   </apex:pageBlockSectionItem><br/>
   
   <apex:pageBlockSectionItem >
    Subject<apex:inputText value="{!subject1}"/>
  </apex:pageBlockSectionItem><br/>
  
  <apex:pageBlockSectionItem >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <apex:inputTextarea value="{!text1}" richText="true" />
  </apex:pageBlockSectionItem>
  <!--file attachment--><br/>
  
     <apex:pageBlockSectionItem >
  <apex:inputFile fileName="{!attach.name}" value="{!attach.body}" styleclass="filetype" id="file" ></apex:inputFile>
  </apex:pageBlockSectionItem><br/>
  <apex:pageBlockSectionItem >
  <apex:outputLabel value="file" for="file"/>
   <apex:commandButton value="send" action="{!sendmai}"/>
 </apex:pageBlockSectionItem>

  </apex:pageBlockSection>
  </apex:pageBlock>
  </apex:form>
</apex:page>

I Hope this is  helpful for you,Please select my answer as best answer.
Thanks,
Varun​
 
Jobelle Belgar 14Jobelle Belgar 14
Thanks, Varun for the help! I tried to test it by adding Circuit__c as the standardController and ComposeEmail as extension to be able to put it in the Circuit page layout.. However, the To address does not auto-populate. I'm not sure what to do.
Jobelle Belgar 14Jobelle Belgar 14
And also, how do I add the email templatein the code? Thank you!
Varun SinghVarun Singh
hi @jobelle
It is easy 
mail.setTemplateId('Your Email Template Id');

Helpful links to set temp id
1-https://th3silverlining.com/2010/05/08/using-basic-email-templates-within-apex/
2-https://techman97.wordpress.com/tag/settargetobjectid/
3-http://anuragsfdc.blogspot.in/2015/02/send-email-using-apex-and-vf-page-by.html

You can also set email temp id by name using in this way
EmailTemplate objEmailTemplate=[select id, name from EmailTemplate where Name='Birthday Emailer'];
email.setTemplateId(objEmailTemplate.id);

If you need any help let me know.
Thanks,
Varun
Jobelle Belgar 14Jobelle Belgar 14
Hi Varun, thank you. Right now, I'm unable to put the code in the Circuit page layout. I don't see the VF page as an option to override my custom button in Circuit object. I have to add the Circuit__c as standard controller and change the ComposeMail apex code as the extension. Now, the fields do not auto-populate.  Thank you so much for your time and kind help!
Varun SinghVarun Singh
Can you send me controller andc vf page page code  to mee ,i can check easily mail me at spnvarun0121@gmail.com
Varun SinghVarun Singh
use in this way

<apex:page standardController="Custom_Object__c" extensions="MyCustomController"> </apex:page>
Jobelle Belgar 14Jobelle Belgar 14
I actually used it that way, however, the controller does not work.
Varun SinghVarun Singh
Hi @ jobelle

Just update your Controller with Constructor(pass  ApexPages.StandardController controller )
public with sharing class ComposeMail {

    public Attachment attach { get; set; }

    public String text1 { get; set; }

    public String subject1 { get; set; }

    public String toaddre { get; set; }

    String tmpID = 'a067F000000dOULQA2';
    Circuit__c c=[Select id,Vendor_type__c from circuit__c where id=:tmpID];
    
    public ComposeMail (ApexPages.StandardController controller){
    if(c!=null){
    
    if(c.Vendor_type__c=='moon')   {
    toaddre ='moon@gmail.com';
    }
    if(c.Vendor_type__c=='space')   {
    toaddre ='space@gmail.com';
    }
    if(c.Vendor_type__c=='stars')   {
    toaddre ='stars@gmail.com';
    }   
    }

    attach=new attachment();
    
     }
   
    public PageReference sendmai() {
        list<Messaging.singleEmailMessage> mails=new list<Messaging.SingleEmailMessage>();
    Messaging.singleEmailMessage mail=new Messaging.SingleEmailMessage();
    list<String> toadd=new List<String>();
    for(string eachemail:toaddre.split(','))
    {
    toadd.add(eachemail);
    }
   //file attachment
     list<Messaging.EmailFileAttachment> lstefa = new list<Messaging.EmailFileAttachment>();
   
    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
    
    efa.setfilename(attach.name);
    efa.setinline(true);
    efa.setbody(attach.body);
    lstefa.add(efa);
    mail.setfileattachments(lstefa);
    mail.setToAddresses(toadd);
    system.debug(toadd);
    mail.setSubject(subject1);
    mail.setTemplateId('Your Email Template Id');
EmailTemplate objEmailTemplate=[select id, name from EmailTemplate where Name='Birthday Emailer'];
    mail.setPlainTextBody(text1);
    mails.add(mail);
   messaging.sendEmail(mails);
    
        return null;
    }

}

 
This was selected as the best answer
Jobelle Belgar 14Jobelle Belgar 14
Thanks, Varun! It worked. The only problem I have now is that the codes to generate the email template does not work. Thanks for your help!
Varun SinghVarun Singh
public with sharing class emailHelper {
  // In a separate class so that it can be used elsewhere
public Circuit__c ckt {get;set;}    
public User myUser { get;set;}
 String toaddre ;
public emailHelper(ApexPages.StandardController stdController)
{ ckt = (Circuit__c)stdController.getRecord(); 
 if(ckt!=null){
    
    if(ckt.Vendor_type__c=='moon')   {
    toaddre ='belgarjobelle@gmail.com';
    }
    if(ckt.Vendor_type__c=='space')   {
    toaddre ='sample@dummy.org';
    }
    if(ckt.Vendor_type__c=='stars')   {
    toaddre ='blabla@email.com';
    }   
}
}

User currentUser = [Select email from User where username = :UserInfo.getUserName() limit 1];  

public  PageReference sendEmail() {
PageReference emailPage = new PageReference('/email/author/emailauthor.jsp');
Map<String, String> params = emailPage.getParameters();
params.put('p3_lkid',ckt.ID); //email will be attached to the activity history of the account where the button was clicked using the ckt.ID
params.put('template_id','00X7F000001GKu8'); /// template ID of the email template to be shown goes here
params.put('rtype','003');
params.put('p24',toaddre); //currentUser.Email showing in "Additional to" field
params.put('p5','support@intelletrace.com'); //email address showing in Bcc field
params.put('new_template','1'); 
params.put('retURL',ApexPages.currentPage().getUrl()); //after send button is clicked, go back to the account where the button was clicked
     
return emailPage;
  
    }  
}