+ 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.