Home > Back-end >  Create filters with GMail API in C#
Create filters with GMail API in C#

Time:09-29

I am trying to create a filter with the Gmail API, using C# in Visual Studio 2019, that checks if an email has an attachment and then adds to it the corresponding label. I already got that label's ID and here's my code:

FilterCriteria criteria = new FilterCriteria
            {
                HasAttachment = true
            };
UsersResource.LabelsResource.GetRequest getLabel =
                gmailService.Users.Labels.Get("[email protected]", "Label_6");
var gotLabel = getLabel.Execute();
var labelId = gotLabel.Id;

FilterAction action = new FilterAction
                {
                    AddLabelIds = {labelId}
                };
Filter filter = new Filter
        {
            Criteria = criteria,
            Action = action
        };
UsersResource.SettingsResource.FiltersResource.CreateRequest requestFilter =
            gmailService.Users.Settings.Filters.Create(filter, "[email protected]");
requestFilter.Execute();

UsersResource.SettingsResource.FiltersResource.ListRequest requestList =
                gmailService.Users.Settings.Filters.List("[email protected]");
// List filters.
IList<Filter> filters = requestList.Execute().Filter;
Console.WriteLine("Filters:");
       if (filters != null && filters.Count > 0)
         {
          foreach (var filterItem in filters)
         {
             Console.WriteLine("{0}", filterItem.Criteria);
         }
}
 else
{
    Console.WriteLine("No filters found.");
}
Console.Read();

After that I'm just trying to print my filters to see if anything's changed. And this is the error I'm getting at the line with the "FilterAction":

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Of course, the gmailService is created and the scopes are all correct. Disclaimer: I'm new in C#. What am I doing wrong here? Any ideas? Thanks in advance!

CodePudding user response:

It appears that FilterAction.AddLabelId is not automatically initialised by the FilterAction constructor, so you need to do it manually:

FilterAction action = new FilterAction
{
    AddLabelIds = new List<string>{labelId}
};
  • Related