在 C# 中使用 GMail API 创建过滤器
Create filters with GMail API in C#
我正在尝试使用 Gmail API 创建一个过滤器,在 Visual Studio 2019 年使用 C#,检查电子邮件是否有附件,然后向其添加相应的标签。我已经获得了该标签的 ID,这是我的代码:
FilterCriteria criteria = new FilterCriteria
{
HasAttachment = true
};
UsersResource.LabelsResource.GetRequest getLabel =
gmailService.Users.Labels.Get("myemail@gmail.com", "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, "myemail@gmail.com");
requestFilter.Execute();
UsersResource.SettingsResource.FiltersResource.ListRequest requestList =
gmailService.Users.Settings.Filters.List("myemail@gmail.com");
// 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();
之后我只是尝试打印我的过滤器以查看是否有任何更改。这是我在“FilterAction”行遇到的错误:
System.NullReferenceException: 'Object reference not set to an
instance of an object.'
当然,gmailService 已经创建,作用域都是正确的。
免责声明:我是 C# 新手。
我在这里做错了什么?有任何想法吗?提前致谢!
FilterAction.AddLabelId
似乎没有被 FilterAction
构造函数自动初始化,所以你需要手动完成:
FilterAction action = new FilterAction
{
AddLabelIds = new List<string>{labelId}
};
我正在尝试使用 Gmail API 创建一个过滤器,在 Visual Studio 2019 年使用 C#,检查电子邮件是否有附件,然后向其添加相应的标签。我已经获得了该标签的 ID,这是我的代码:
FilterCriteria criteria = new FilterCriteria
{
HasAttachment = true
};
UsersResource.LabelsResource.GetRequest getLabel =
gmailService.Users.Labels.Get("myemail@gmail.com", "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, "myemail@gmail.com");
requestFilter.Execute();
UsersResource.SettingsResource.FiltersResource.ListRequest requestList =
gmailService.Users.Settings.Filters.List("myemail@gmail.com");
// 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();
之后我只是尝试打印我的过滤器以查看是否有任何更改。这是我在“FilterAction”行遇到的错误:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
当然,gmailService 已经创建,作用域都是正确的。 免责声明:我是 C# 新手。 我在这里做错了什么?有任何想法吗?提前致谢!
FilterAction.AddLabelId
似乎没有被 FilterAction
构造函数自动初始化,所以你需要手动完成:
FilterAction action = new FilterAction
{
AddLabelIds = new List<string>{labelId}
};