0

Through Apex code, we want All users to follow a particular user. While trying to do that, Salesforce generates email to particular user. Email is getting triggered even if email settings is switched off before adding records in EntitySubscription. Do we have any other settings which has to be switched off before creating record in EntitySubscription.

Following code works if there is only 1 user to follow but doesn't work if we have 15 users to follow a particular user.

Sample code.

Id userToFollow ='0051I000000WqWT';
List<User> othersList = [select id from user where id !=:userToFollow and usertype='Standard' and isactive=true];
User userObj = new User(id=userToFollow,UserPreferencesDisableAllFeedsEmail = true);
update userObj;
List<EntitySubscription> esList = new List<EntitySubscription>();
for(User userO : othersList) {
    EntitySubscription entitySubsObj = new EntitySubscription();
    entitySubsObj.ParentId = userToFollow;
    entitySubsObj.SubscriberId = userO.id;
    esList.add(entitySubsObj);
}
insert esList;
userObj.UserPreferencesDisableAllFeedsEmail = false;
update userObj;
0

I tried to test my theory but I can't because my dev org only has two licences which means I can't test the situation with more than 1 user that you said you have. My Theory is that the emails are sent asynchronously and that the user preference is turned back on before the emails are actually sent which is why it doesn't work. Consider creating a future method to turn the UserPreferencesDisableAllFeedsEmail back off instead:

@future
public static void EnableEmails(Id UserId) {
    update new User(
        Id = UserId,
        UserPreferencesDisableAllFeedsEmail = false
    );
}

Then Try:

Id userToFollow ='0051I000000WqWT';
List<User> othersList = [select id from user where id !=:userToFollow and usertype='Standard' and isactive=true];
User userObj = new User(id=userToFollow,UserPreferencesDisableAllFeedsEmail = true);
update userObj;
List<EntitySubscription> esList = new List<EntitySubscription>();
for(User userO : othersList) {
    EntitySubscription entitySubsObj = new EntitySubscription();
    entitySubsObj.ParentId = userToFollow;
    entitySubsObj.SubscriberId = userO.id;
    esList.add(entitySubsObj);
}
insert esList;

EnableEmails(userToFollow );
1
  • 1
    We are doing this batch, already tried creating records in execute and switching on email in finish but no success. – Ashish Narang Apr 23 '18 at 6:04

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.