function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pranav ChitransPranav Chitrans 

Apex Trigger to send email when contact inserted

hi gyus... This code is working fine..when ever I insert or update record it sends email.. but I am quite confused  so plz explain me the use of line 16,line 19,line 25 & what is the use of flag... and tell me that is messaging.singleEmailMessage is defined keyword...??
Last but not the least I want to edit the code in such a way that if i insert the data with dataloader where there is more than one contact then send email to more than one contact is inserted at a time....

************apex class**********
public with sharing class HelperContactTrigger {
    public static List<Contact> sendEmail(List<Contact>Contacts)
    {
     //query on template object
        EmailTemplate et=[Select id from EmailTemplate where name=:'Sales: New Customer Email'];

        //list of emails
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();   
        
        for(Contact con : Contacts)
        {
          //check for Account
            if(con.AccountId != null && con.Email != null){

                //initiallize messaging method
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

                //set object Id
                singleMail.setTargetObjectId(con.Id);

                //set template Id
                singleMail.setTemplateId(et.Id);

                //flag to false to stop inserting activity history
                singleMail.setSaveAsActivity(false);

                //add mail
                emails.add(singleMail);
            }
        }
            //send mail
        Messaging.sendEmail(emails);

        return Contacts;          
        
    }

    public static List<Contact> sendEmailafter(List<Contact>Contacts)
    {
    //query on template object
        EmailTemplate et=[Select id from EmailTemplate where name=:'Sales: New Customer Email'];

        //list of emails
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();   
        
        for(Contact con : Contacts)
        {
          //check for Account
            if(con.AccountId != null && con.Email != null){

                //initiallize messaging method
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

                //set object Id
                singleMail.setTargetObjectId(con.Id);

                //set template Id
                singleMail.setTemplateId(et.Id);

                //flag to false to stop inserting activity history
                singleMail.setSaveAsActivity(false);

                //add mail
                emails.add(singleMail);
            }
         }
            //send mail
        Messaging.sendEmail(emails);

        return Contacts;          
        }
    }

*********Apex trigger********
trigger SendEmailToAccount on Contact (after insert,after update) 
{
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert )
        { 
            //helper class for single email but bulk messages
            HelperContactTrigger.sendEmail(trigger.new);
        }
    }
        if(trigger.isAfter && trigger.isUpdate )
        {           
         HelperContactTrigger.sendEmailafter(trigger.new);
        }
}

 
Ajay K DubediAjay K Dubedi
Hi Pranav,

according to your code
line 16 calls the standard the messaging class method SingleEmailMessage which is used for sending the massages.
line 19 setTargetObjectId(ID)
Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data. 
http://salesforce.stackexchange.com/questions/82583/singleemailmessage-settargetobjectid-but-do-not-send-to-target
line 25--setSaveAsActivity(Boolean)
Optional. The default value is true, meaning the email is saved as an activity. This argument only applies if the recipient list is based on targetObjectId or targetObjectIds. If HTML email tracking is enabled for the organization, you will be able to track open rates.
http://meltedwires.com/2014/11/10/apex-code-tip-sending-email-to-salesforce-users/

Thanks.
sales@myvarmasales@myvarma
  EmailTemplate et=[Select id from EmailTemplate where name=:'Sales: New Customer Email'];   

with out calling this template 

how to write template their it self?
help me
Pranav ChitransPranav Chitrans
Hi,
@sales@myvarma

You can do something like this :
Apex Controller
public  class acctTemplt
{
    public Id accountId {get;set;}
    public List<Opportunity> getopptys()
    {
        List<Opportunity> oppty;
        oppty = [SELECT Name, StageName FROM Opportunity WHERE Accountid =: accountId];
        return oppty;
    }
}

Component:
<apex:component controller="acctTemplt" access="global">
    <apex:attribute name="AcctId" type="Id" description="Id of the account" assignTo="{!accountId}"/>
    <table border = "2" cellspacing = "5">
        <tr>
            <td>Opportunity Name</td>
            <td>Opportunity Stage</td>                
        </tr>
        <apex:repeat value="{!opptys}" var="o">
        <tr>
            <td>{!o.Name}</td>
            <td>{!o.StageName}</td>              
        </tr>
        </apex:repeat>        
    </table>
</apex:component>

Visualforce Email template:
<messaging:emailTemplate subject="List of opportunity" recipientType="User" relatedToType="Account">
    <messaging:htmlEmailBody >
    Hi,<br/>
    Below is the list of opportunities for your account {!relatedTo.Name}.<br/><br/>
    <c:OpptyList AcctId="{!relatedTo.Id}" /><br/><br/>
    <b>Regards,</b><br/>
    {!recipient.FirstName}
    </messaging:htmlEmailBody>
</messaging:emailTemplate>

Or you can directly put the HTML code to design your desired custom template inside the VF page as well

Thnaks
Pranav.
Abdulla d 5Abdulla d 5
Check the following code it may helpful to u.
Whenever an Account Name is modified send an email notification to the contact of an account.
*/
public class Account_Email_Notififcation {
    public static void sendMail(Map<id,Account> oldmap,Map<ID,Account> newmap){
        List<ID> AccID =New LIst<ID>();
        for(id key:oldmap.keySet()){
            Account old=oldmap.get(key);
            Account Newk=newmap.get(key);
            if(old.Name!=newk.Name){
                accID.add(key);
            }
        }
        List<contact> con=[select id, Email from Contact where AccountID in :accID];
        List<string> toadd= new List<string>();
        for(Contact c: con){
            toadd.add(c.Email);     
            Messaging.SingleEmailMessage msg1=new Messaging.SingleEmailMessage();
            msg1.setToAddresses(toadd);
            msg1.setSubject('Your Account Name is modified');
            msg1.setPlainTextBody('Dear, Account holder Your Account name is modified');
            msg1.setSenderDisplayName('ARYAN');
            Messaging.Email[] emails=new Messaging.Email[]{msg1};
            Messaging.sendEmail(emails);
        }               
       update con;   
    }
}

trigger Account_Name_modifed_email on Account (after insert,after update) {
    Account_Email_Notififcation.sendMail(Trigger.oldmap, trigger.newmap);
}
damion medamion me

Best Visual Voicemail Apps of 2021

Voicemail makes things much simpler letting others know when you are busy and delivers message. Here are the best voicemail apps to check
https://androidpowerhub.com/which-are-the-best-voicemail-apps/

Jenna CovingtonJenna Covington
Well, I think you can get the best help regarding these codes by simply searching for them on google. When I need help regarding my project I also search for it on google and found https://www.bestcustomessay.org/write-my-term-paper/ site. That's why I am suggesting you this. Hope this will help you out.
Roxely MaiasRoxely Maias
Introducing the Salesforce Platform
At Salesforce, we've grouped our services into clouds(http://blogeral.com). We have Sales Cloud for CRM, Service Cloud for customer support, and several other clouds that help companies solidify their business functions (https://popfay.com/blog). While each of these clouds has a specific purpose, they have one thing in common: the power of the Salesforce Platform.
Sam Smith 67Sam Smith 67
Forget the overwhelming schedule and take some time off to relax and enjoy college life with friends master thesis help (https://www.thesiswritingservice.com/). As much as you need to ace all your assignments, you need to rejuvenate and get time away from books.
Sprutiraj Panda 7Sprutiraj Panda 7

public class Emailmanager {

    public static void sendingEmail()

    {

        Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();

        String[] sendingTo = new String[]{'xxxx21@gmail.com'}; 

            semail.setToAddresses(sendingTo); 

        String[] sendingToBccAdd = new String[]{'xxx21@gmail.com'}; 

            semail.setBccAddresses(sendingToBccAdd); 

        String[] sendingTocAdd = new String[]{'xxxx21@gmail.com'}; 

            semail.setCcAddresses(sendingTocAdd); 

        semail.setSubject('New Contact Record was inserted'); 

        semail.setPlainTextBody('Hi New Contact has been inserted Successfully!!!'); 

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});  
   } 

}

Trigger of the class
trigger ContactInsert on Contact(after insert,after Update) {

    if(trigger.isInsert){
        Emailmanager.sendingEmail();
    }
  
    }
 
simply buzzes 9simply buzzes 9
I got it and really appreciate your time and effort, But could you please suggest me about the Kbc head office Mumbai (https://kbcwins.com/kbc-head-office-number-contact-number-to-kbc-00019152084400/) I'll be very ver thanksfull to you. I am waiting for your response. 
hijir Saharhijir Sahar
alterativepharma (https://www.google.com/url?sa=t&url=https%3A%2F%2Falterativepharma.com.br) alterativepharma (http://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&tid=9BB77FDA801248A5AD23FDBDD5922800&url=https%3A%2F%2Falterativepharma.com.br) alterativepharma (https://www.google.com/url?sa=t&url=https%3A%2F%2Falterativepharma.com.br) alterativepharma (https://www.google.com/url?sa=t&url=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://www.google.com/url?sa=t&url=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://www.youtube.com/redirect?event=channel_description&q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://www.youtube.com/redirect?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://t.me/iv?url=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://www.t.me/iv?url=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://new.creativecommons.org/choose/results-one?q_1=2&q_1=1&field_commercial=n&field_derivatives=sa&field_jurisdiction=&field_format=Text&field_worktitle=Blog&field_attribute_to_name=Lam%20HUA&field_attribute_to_url=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://creativecommons.org/choose/results-one?q_1=2&q_1=1&field_commercial=n&field_derivatives=sa&field_jurisdiction=&field_format=Text&field_worktitle=Blog&field_attribute_to_name=Lam%20HUA&field_attribute_to_url=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://legal.un.org/docs/doc_top.asp?path=../ilc/documentation/english/a_cn4_13.pd⟪=Ef&referer=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://m.ok.ru/dk?st.cmd=outLinkWarning&st.rfn=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://www.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (http://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&tid=9BB77FDA801248A5AD23FDBDD5922800&url=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://www.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://plus.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://plus.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://plus.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://plus.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://plus.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://plus.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F) alterativepharma (https://plus.google.com/url?q=https%3A%2F%2Falterativepharma.com.br%2F)
house of outsourcinghouse of outsourcing
Internal medicine physicians are consistently occupied in managing wide scope of medical problems identified with the maturing that incorporate the ongoing illnesses and the weakening conditions. These constant infections are more normal in more established individuals when contrasted with the more youthful ones and such patients need a broad consideration.
https://houseofoutsourcing.com/speciality/internal-medicine-billing-services/
Raj Sekhar 32Raj Sekhar 32
I got it and really appreciate your time and effort, But could you please suggest to me about the Kbc head office Mumbai I'll be very very thankful to you. I am waiting for your response. KBC Lottery Number Check (https://kbclotterywinner.info/)