C# gmail api为特定历史id返回null。从云发布/订阅推送订阅接收的历史id

C# gmail api为特定历史id返回null。从云发布/订阅推送订阅接收的历史id,c#,gmail-api,C#,Gmail Api,从云发布/订阅推送服务中,我获得了一个历史id。使用该历史id,我试图读取最近邮件的,但返回null 我已经配置了云发布/订阅推送订阅,并在“未读”标签上添加了一个手表 情景1: 我收到了推送通知。从推送通知中,我获取了历史id以获取最近的消息。它将返回空值 情景2: 我已登录到配置的邮件id,然后将邮件加载到收件箱中。之后,如果我尝试阅读,我会得到历史记录列表 static string[] Scopes = { GmailService.Scope.MailGoogleCom };

从云发布/订阅推送服务中,我获得了一个历史id。使用该历史id,我试图读取最近邮件的,但返回null

我已经配置了云发布/订阅推送订阅,并在“未读”标签上添加了一个手表

情景1: 我收到了推送通知。从推送通知中,我获取了历史id以获取最近的消息。它将返回空值

情景2: 我已登录到配置的邮件id,然后将邮件加载到收件箱中。之后,如果我尝试阅读,我会得到历史记录列表

    static string[] Scopes = { GmailService.Scope.MailGoogleCom };
    static void Main(string[] args)
    {
     string UserId = "####.gmail.com";
     UserCredential credential;
     using (var stream =
                    new FileStream("client_secret_#####.json", FileMode.Open, FileAccess.Read))
                {             
                    string credPath = "token.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        UserId,
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                    Console.WriteLine("Credential file saved to: " + credPath);
                }

     var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

     List<History> result = new List<History>();
                UsersResource.HistoryResource.ListRequest request = service.Users.History.List(UserId);
    //history id received from cloud pub/sub push subscription.
                request.StartHistoryId = Convert.ToUInt64("269871");

    do
                {
                    try
                    {
                        ListHistoryResponse response = request.Execute();
                        if (response.History != null)
                        {
                            result.AddRange(response.History);
                        }
                        request.PageToken = response.NextPageToken;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An error occurred: " + e.Message);
                    }
                } while (!String.IsNullOrEmpty(request.PageToken));


      foreach (var vHistory in result)
                {
                    foreach (var vMsg in vHistory.Messages)
                    {
                        string date = string.Empty;
                        string from = string.Empty;
                        string subject = string.Empty;
                        string body = string.Empty;

                        var emailInfoRequest = service.Users.Messages.Get(UserId, vMsg.Id);
                        var emailInfoResponse = emailInfoRequest.Execute();
                        if(emailInfoResponse!= null)
                        {
                            foreach (var mParts in emailInfoResponse.Payload.Headers)
                            {
                                if (mParts.Name == "Date")
                                {
                                    date = mParts.Value;
                                }
                                else if (mParts.Name == "From")
                                {
                                    from = mParts.Value;
                                }
                                else if (mParts.Name == "Subject")
                                {
                                    subject = mParts.Value;
                                }
                                if (date != "" && from != "")
                                {
                                    if (emailInfoResponse.Payload.Parts != null)
                                    {
                                        foreach (MessagePart p in emailInfoResponse.Payload.Parts)
                                        {
                                            if (p.MimeType == "text/html")
                                            {
                                                byte[] data = FromBase64ForUrlString(p.Body.Data);
                                                body = Encoding.UTF8.GetString(data);
                                            }
                                            else if(p.Filename!=null && p.Filename.Length>0)
                                            {
                                                string attId = p.Body.AttachmentId;
                                                string outputDir = @"D:\#####\";
                                                MessagePartBody attachPart = service.Users.Messages.Attachments.Get(UserId, vMsg.Id, attId).Execute();
                                                String attachData = attachPart.Data.Replace('-', '+');
                                                attachData = attachData.Replace('_', '/');
                                                byte[] data = Convert.FromBase64String(attachData);
                                                File.WriteAllBytes(Path.Combine(outputDir, p.Filename), data);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        byte[] data = FromBase64ForUrlString(emailInfoResponse.Payload.Body.Data);                                   
                                        body = Encoding.UTF8.GetString(data);
                                    }
                                }
                            }
                        }
                    }
                }
 public static byte[] FromBase64ForUrlString(string base64ForUrlInput)
    {
        int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
        StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
        result.Append(String.Empty.PadRight(padChars, '='));
        result.Replace('-', '+');
        result.Replace('_', '/');
        return Convert.FromBase64String(result.ToString());
    }

    }
static string[]Scopes={GmailService.Scope.MailGoogleCom};
静态void Main(字符串[]参数)
{
字符串UserId=“#####.gmail.com”;
用户凭证;
使用(var)流=
新的文件流(“客户机加密”;“json”;“FileMode.Open”,FileAccess.Read))
{             
字符串credPath=“token.json”;
凭证=GoogleWebAuthorizationBroker.AuthorizationAsync(
GoogleClientSecrets.Load(stream.Secrets),
范围,
用户ID,
取消令牌。无,
新文件数据存储(credPath,true))。结果;
Console.WriteLine(“凭证文件保存到:”+credPath);
}
var service=new-GmailService(new-BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=ApplicationName,
});
列表结果=新列表();
UsersResource.HistoryResource.ListRequest请求=service.Users.History.List(UserId);
//从云发布/订阅推送订阅接收的历史id。
request.StartHistoryId=Convert.ToUInt64(“269871”);
做
{
尝试
{
ListHistoryResponse=request.Execute();
if(response.History!=null)
{
结果.添加范围(响应.历史记录);
}
request.PageToken=response.NextPageToken;
}
捕获(例外e)
{
Console.WriteLine(“发生错误:+e.Message”);
}
}而(!String.IsNullOrEmpty(request.PageToken));
foreach(结果中的var历史记录)
{
foreach(vHistory.Messages中的var vMsg)
{
string date=string.Empty;
string from=string.Empty;
string subject=string.Empty;
string body=string.Empty;
var emailInfoRequest=service.Users.Messages.Get(UserId,vMsg.Id);
var emailInfoResponse=emailInfoRequest.Execute();
if(emailInfoResponse!=null)
{
foreach(emailInfoResponse.Payload.Headers中的var mpart)
{
如果(mpart.Name==“日期”)
{
日期=mParts.Value;
}
else if(mpart.Name==“From”)
{
from=mpart.Value;
}
else if(mpart.Name==“主题”)
{
主题=mParts.Value;
}
如果(日期!=“”&from!=“”)
{
if(emailInfoResponse.Payload.Parts!=null)
{
foreach(emailInfoResponse.Payload.Parts中的MessagePart p)
{
if(p.MimeType==“text/html”)
{
byte[]data=FromBase64ForUrlString(p.Body.data);
body=Encoding.UTF8.GetString(数据);
}
else if(p.Filename!=null&&p.Filename.Length>0)
{
string attId=p.Body.AttachmentId;
字符串outputDir=@“D:\\\\\\\\\\\\\\”;
MessagePartBody attachPart=service.Users.Messages.Attachments.Get(UserId,vMsg.Id,attId).Execute();
字符串attachData=attachPart.Data.Replace('-','+');
attachData=attachData.Replace(“”,“/”);
字节[]数据=Convert.FromBase64String(attachData);
File.writealBytes(Path.Combine(outputDir,p.Filename),数据);
}
}
}
其他的
{
byte[]data=FromBase64ForUrlString(emailInfoResponse.Payload.Body.data);
body=Encoding.UTF8.GetString(数据);
}
}
}