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
cool_codingcool_coding 

Sending Email to Opportunity team Members (people present in the list) found on Opportunity

I need help on the above mention subject area.
Actually, I am working with a batch.
I have a object Contrat__c which is related to an opportunity by a lookup field Reference_proposition_commerciale__c, and on the opportunity we have Opportunity Team members.
My aim is: When this field is checked ContratPerdue__c (this field in found in Contrat__C, I have to send a mail to all the people which is in Opportunity Team Member and whose role is the following :ATM, OR, ATM_Role_Rcli, OR Role_CAC_Charg_Affaire_Commerciale I have done a query in OpportunityTeamMember and the above mentionned roles I ha
global class Batch_EnvoieMailContratPerdu implements Database.Batchable<sObject>{
    
	global Set<Id> oppId = new Set<Id>();
    global Map<Id,Contrat__c>  conMapUpdate = new Map<Id,Contrat__c>(); 
    
  global Database.QueryLocator start(Database.BatchableContext BC){
         String query = null;
        
        /*Une requete sera fait sur 
		les contrats rattachés à la PC avec statut 'Résilié' ou 'Caduque' et ContratPerdue__c = false. */
        
        query = 'SELECT Id';
        query += ', Reference_proposition_commerciale__c,Reference_proposition_commerciale__r.Type_de_flexibilite__c, Statut__c';
        query += ', Reference_proposition_commerciale__r.Nombre_site_actualise__c, Reference_proposition_commerciale__r.Borne_basse__c';
        query += ', ContratPerdue__c';
        query += ' FROM Contrat__c';
        query += ' WHERE ContratPerdue__c = false';
        query += ' AND Reference_proposition_commerciale__c != null';
        query += ' AND (Statut__c = \'Résilié\'';
        query += ' OR Statut__c = \'Caduque\')';
       
         System.debug('query is'+query);
         return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Contrat__c> aConList){
        try{
        
    /*Si le champ "Type de flexibilité (%)" = 'Nombre de sites' sur la PC ET "Nombre de site actualisé" < Borne basse 
        OU 
        Si le champ "Type de flexibilité (%)" = 'Volume' sur la PC ET "Volume actualisée annuel (MWh)" < Borne basse */
       
            for (Contrat__c con : aConList){
                if((Label.CL_PC_Nombre_de_sites.equalsIgnoreCase(con.Reference_proposition_commerciale__r.Type_de_flexibilite__c) &&
                    con.Reference_proposition_commerciale__r.Nombre_site_actualise__c < con.Reference_proposition_commerciale__r.Borne_basse__c )
                   
                   ||(Label.CL_PC_Volume.equalsIgnoreCase(con.Reference_proposition_commerciale__r.Type_de_flexibilite__c) &&
                      con.Reference_proposition_commerciale__r.Nombre_site_actualise__c < con.Reference_proposition_commerciale__r.Borne_basse__c)){
                          
                          /*Mettre a jour le champ ContratPerdue__c = true sur les contrats de la requete.*/
                          con.ContratPerdue__c = true;
                          oppId.add(con.Reference_proposition_commerciale__c);
                          System.debug('oppId values in loop'+oppId);
						  conMapUpdate.put(con.id,con);
                            }
                 System.debug('con values out'+con);
                                
            }
            if(conMapUpdate != null && conMapUpdate.values() != null && conMapUpdate.values().size()>0){
            UtilsBypass.SKIP_STRIGGER_MAP.put('ContractBeforeUpdate','skip trigger');
            UtilsBypass.SKIP_STRIGGER_MAP.put('ContractAfterUpdate','skip trigger');
            UtilsBypass.SKIP_STRIGGER_MAP.put('ContractAfterInsert','skip trigger');
            UtilsBypass.SKIP_STRIGGER_MAP.put('ContractBeforeInsert','skip trigger');
            Database.update(conMapUpdate.values());
            UtilsBypass.SKIP_STRIGGER_MAP.remove('ContractBeforeUpdate');
            UtilsBypass.SKIP_STRIGGER_MAP.remove('ContractAfterUpdate');
            UtilsBypass.SKIP_STRIGGER_MAP.remove('ContractAfterInsert');
            UtilsBypass.SKIP_STRIGGER_MAP.remove('ContractBeforeInsert');
            System.debug('conMapUpdate values in '+conMapUpdate);
            }
             System.debug('conListUpdate values out '+conMapUpdate.values());
   
        	System.debug('oppId values'+oppId);
        
        
        }catch(Exception e){
            System.debug('Error1 : '+e.getMessage());
            System.debug('Error line1 : '+e.getLineNumber());
        }
        
     }
          
   
    global void finish(Database.BatchableContext BC){
        try{
            system.debug('entering finish loop');
		/*Faire une requete sur l'objet OpportunityTeamMember pour avoir l'addresse email */
		if(oppId != null
		   && oppId.size() > 0){
			
			Map<Id, List<OpportunityTeamMember>> oppTeamListMap = new Map<Id, List<OpportunityTeamMember>>();

			for(OpportunityTeamMember oppTeam : [SELECT id, UserId, User.Email, TeamMemberRole
												 FROM OpportunityTeamMember
												 WHERE OpportunityId IN : oppId
												 AND (TeamMemberRole =: Label.CL00017_ATM 
												 OR TeamMemberRole =: Label.CL00396_ATM_Role_Rcli 
												 OR TeamMemberRole =: Label.CL_CTM_Role_CAC_Charg_Affaire_Commerciale) 
												 ORDER BY OpportunityId LIMIT 50000]){
			 System.debug('oppTeam values'+oppTeam);	
                                                     
				//Order Opportunity and fill map withlistow
				if(oppTeamListMap.containsKey(oppTeam.OpportunityId)){
					oppTeamListMap.get(oppTeam.OpportunityId).add(oppTeam);
				}else{ 
					oppTeamListMap.put(oppTeam.OpportunityId, new List<OpportunityTeamMember> { oppTeam });
				}
			}
			System.debug('oppTeamListMap values'+oppTeamListMap);	
               
			if(oppTeamListMap.size() > 0){ 
				List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
				Messaging.SingleEmailMessage mail = null;
				List<String> emailAddressesList = new List<String>();

				for(Id oppId : oppTeamListMap.keySet()){ 
					emailAddressesList = new List<String>();

					for(OpportunityTeamMember ot : oppTeamListMap.get(oppId)){ 
						emailAddressesList.add(ot.User.Email);
					}
                    System.debug('emailAddressesList values'+emailAddressesList);

					String body = 'TEST';

					mail = new Messaging.SingleEmailMessage();
					//mail.setTemplateId(template[0].Id);
					//mail.setTargetObjectId(currentUser[0].Id);
					mail.setToAddresses(emailAddressesList);
					mail.setCcAddresses(new List<String> {'test@hotmail.com'});
					mail.setSubject('TEST');
					mail.setHtmlBody(body);
					mails.add(mail);
				}
                System.debug('value sof mail'+mail);

				if(mails.size() > 0){
					Messaging.sendEmail(mails);
				}
			}
		}
      }
      catch(Exception e){
            System.debug('Error2 : '+e.getMessage());
            System.debug('Error line2 : '+e.getLineNumber());
        }
  
    }
   
}

ve put it in a Label.
My problem is, this field ContratPerdue__c is being checked, ie ContratPerdue__c =true, but the email is not being send.
Can anyone please help me.
Below is my code.
UC InnovationUC Innovation
Does the code execution get to line 110?  If so, perhaps it's an issue with the email delivery option:

https://help.salesforce.com/HTViewHelpDoc?id=emailadmin_deliverability.htm

If you are using sandbox, by default, it is set to 'No access'.
cool_codingcool_coding
I have resolve it.
The codes in the finish Method, I have put alle the code in the Execute Method.
I have done so, because I have notice that previously, I was not getting the values of these 2 debug logs in the Finish method. I needed these values to continue the work in Finish Method, The values were only available in the execute Method.
So I have put all the code from the Finish to the Execute Method, and it works correctly.
 
System.debug('conListUpdate values out '+conMapUpdate.values());

 System.debug('oppId values'+oppId);

 
UC InnovationUC Innovation
Glad that you were able to figure this out.