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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.