I have a batch which after creation of records send out emails to the opportunity Account manager for which new record is created.
// Get All Opportunities
set<id> Billoppid= new set<id>();
for ( Billing_Month__c bm : ListofBillingMonthstoinsert) {
Billoppid.add(bm.Opportunity__c);}
// Get Account Managers
List < opportunity > Ownerlist = new list < opportunity > ([Select id,Owner.Email, Account_Manager_lookup__c, Name from opportunity where id in : Billoppid]);
for (opportunity Opp: Ownerlist) {
if ( Opp.Account_Manager_lookup__c!=null)
Userid.add(Opp.Account_Manager_lookup__c);
}
// Get Account Manager emails
list < user > AMlistemails = new list < user > ([select id, email from user where id in : Userid]);
map < id, string > Mapamuseremail = new map < id, string > ();
List<Messaging.SingleEmailMessage> mails = new
List<Messaging.SingleEmailMessage>();
for (user u: AMlistemails) {
Mapamuseremail.put(u.id, u.email);}
for (opportunity opp1:Ownerlist ) {
if (Mapamuseremail.containskey(opp1.Account_Manager_lookup__c) && opp1.Account_Manager_lookup__c != null){
ListAMandOwneremail.add(Mapamuseremail.get(opp1.Account_Manager_lookup__c));}
// send email to AM's
Messaging.SingleEmailMessage mail = new
Messaging.SingleEmailMessage();
string mbody;
if (ListAMandOwneremail.size()>0){
mail.setToAddresses(ListAMandOwneremail);}
else
{
mail.setToAddresses(ccadd);}
mail.setccAddresses(ccadd);
mail.setUseSignature(FALSE);
mail.setSubject('Billing Month Created');
mBody = '<html><body> Opportunity: ' + opp1.Name + ' has new Billing Months created. </body></html>';
mail.setHtmlBody(mBody);
mails .add(mail);
}
if ( mails.size()>0){
Messaging.sendEmail(mails);
}
}
This code captures all the opportunities Account managers and send out emails to all, because of which even those Account manager who don't belong to an opportunity still gets the mail.
How to send out mail details of an particular opportunity for it's Account manager alone?