Can I tag any user in chatter feed (@mention) from apex?

List<Opportunity> testList = [SELECT id,name from opportunity where name LIKE '%test%'];
List<feeditem> testfeed = new List<feedItem>();
for(opportunity opp:testList){
FeedItem post = new FeedItem();
    String fullFileURL = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ opp.id;
    post.parentId = '0054B000000Tn0Y';
    post.Body = 'This is the action item @[username]'+opp.name;
    post.LinkUrl = fullFileURL ;
insert testfeed;
  • Not with FeedItem. You need to use the ConnectApi for that. Some light Google research should get you what you need.
    – Adrian Larson
    Apr 21, 2016 at 18:28
  • I tried doing that Adrian, but was getting the compilation error: ConnectApi.ChatterFeeds.postFeedItem(null,ConnectApi.FeedType.News, 'me', input, null); The error is:Method was removed after version 31.0: postFeedItem
    – Anurag
    Apr 21, 2016 at 18:31
  • Hmm have you tried compiling a class at a lower version to use it? Not aware of any replacement for it off the top of my head.
    – Adrian Larson
    Apr 21, 2016 at 18:32

2 Answers 2


Here's a structure you can utilize for mentions:

    List<ConnectApi.BatchInput> batchInputs = new List<ConnectApi.BatchInput>();

    for(sObject c : [SOQL Query]){

         ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
         ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
         ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
         ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

         messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
         //Mention user here
         mentionSegmentInput.id = c.OwnerId;

         textSegmentInput.text = '\n'+' Chatter text here';

         feedItemInput.body = messageBodyInput;
         feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
         feedItemInput.subjectId = c.Id;

         ConnectApi.BatchInput batchInput = new ConnectApi.BatchInput(feedItemInput);


     ConnectApi.ChatterFeeds.postFeedElementBatch(Network.getNetworkId(), batchinputs);
  • +1 This code is basically outlined in this link.
    – sfdcfox
    Apr 21, 2016 at 18:36
  • @sfdcfox How do i get notified when i tag myself?
    – Anurag
    Apr 21, 2016 at 19:20
  • @AnuragA I believe you will not be notified on self mention Jun 24, 2016 at 22:56

Also worth looking at this helper class on GitHub from the Chatter folks

You can then just call a method like this:

postFeedItemWithMentions(String communityId, String subjectId, String textWithMentions)

and it will post to the record and parse the mentions for you

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .