1

I am trying to use salesforce opt-out feature via APEX code. According to the doc, Salesforce should respect the opt-out field of contact if we use the ID of an object as a target. When I am using Contact ID as TargetObjectID then it is respecting opt-out field but if I use User ID of the same user then it is not respecting opt-put setting(Sending an email to the same user). According to my use case, I'll get a mixed list of contact ID as well as User id to send emails.

So I like to know that I am doing something wrong or this is the expected behavior of Salesforce

This is working:

User  user =  [Select Id,Name,  userName, firstName, lastName, Email,  ContactId,  IsActive from User limit 1];
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
mail.setOptOutPolicy('FILTER');
email.setTargetObjectId(user.ContactId); //Contact ID of User
.........
List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>();
emailList.add(email);
List<Messaging.SendEmailResult> results = Messaging.sendEmail(emailList,false);

This is not working:

User  user =  [Select Id,Name,  userName, firstName, lastName, Email,  ContactId,  IsActive from User limit 1];
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
mail.setOptOutPolicy('FILTER');
email.setTargetObjectId(user); //User ID of user object
.........
List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>();
emailList.add(email);
List<Messaging.SendEmailResult> results = Messaging.sendEmail(emailList,false);
2
  • Instead of using setTargetObjectID can you try using toAddress instead? developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… Sep 4, 2018 at 14:05
  • @PranayJaiswal 'toAddress' is not working for me. 'ToAddress' is not respecting opt-out setting when I used contact ID which was worked for 'setTargetObjectID'. Seems there are some other settings require to work properly. Sep 5, 2018 at 7:33

0

You must log in to answer this question.

Browse other questions tagged .