无法使用Users.messages:修改Google API选项

时间:2017-03-14 08:18:08

标签: google-api gmail google-api-dotnet-client

有人可以帮我解决以下异常吗? 这是我用来将Inbox消息移动到另一个标签的.Net代码

{
List<String> labelsToAdd = new List<string>();
labelsToAdd.Add("Label_1");
//List<String>`enter code here` labelsToRemove = new List<string>();
//labelsToRemove.Add("INBOX");

ModifyMessageRequest mods = new ModifyMessageRequest();
mods.AddLabelIds = labelsToAdd;
//mods.RemoveLabelIds = labelsToRemove;

gmail.Users.Messages.Modify(mods, usr, email.Id).Execute();
}

我收到的错误就是这个

  

GoogleAPIException - {&#34;发生错误,但错误响应可能   不被反序列化&#34;}

     

Newtonsoft.Json.JsonReaderException - {&#34;意外字符   在解析值时遇到:&lt;。路径&#39;&#39;,第0行,第0位。&#34;}

     

StackTrace - 在Newtonsoft.Json.JsonTextReader.ParseValue()

     

在Newtonsoft.Json.JsonTextReader.Read()

     

at Newtonsoft.Json.JsonReader.ReadAndMoveToContent()

     

在   Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader   reader,JsonContract contract,Boolean hasConverter)

     

在   Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader   reader,Type objectType,Boolean checkAdditionalContent)

     

在Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader   reader,Type objectType)

     

在Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader,Type   的objectType)

     

at Newtonsoft.Json.JsonConvert.DeserializeObject(String value,Type   type,JsonSerializerSettings settings)

     

at Newtonsoft.Json.JsonConvert.DeserializeObject [T](String value,   JsonSerializerSettings设置)

     

at Google.Apis.Json.NewtonsoftJsonSerializer.Deserialize [T](String   输入)   C:\蜂房\ V1.21 \ Google处理API-DOTNET客户端\ SRC \支持\ GoogleApis.Core \蜜蜂\的Json \ NewtonsoftJsonSerializer.cs:线   148

     

在   Google.Apis.Services.BaseClientService.d__34.MoveNext()   在   C:\ Apiary \ v1.21 \ google-api-dotnet-client \ Src \ Support \ GoogleApis \ Apis \ Services \ BaseClientService.cs:第288行

1 个答案:

答案 0 :(得分:0)

您所使用的代码对我来说很好,我认为您可能遇到的唯一问题是labelsToAdd.Add("Label_1");可能不是标签ID。但是,当我尝试发送无效标签时,我正在

  

标签无效:adfadsfdsf [400]

这是我使用的代码。

认证

/// <summary>
/// This method requests Authentcation from a user using Oauth2.  
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static GmailService AuthenticateOauthGmail(string clientSecretJson, string userName)
{
    try
    {
        if (string.IsNullOrEmpty(userName))
            throw new ArgumentNullException("userName");
        if (string.IsNullOrEmpty(clientSecretJson))
            throw new ArgumentNullException("clientSecretJson");
        if (!File.Exists(clientSecretJson))
            throw new Exception("clientSecretJson file does not exist.");

        // These are the scopes of permissions you need. It is best to request only what you need and not all of them
        string[] scopes = new string[] { GmailService.Scope.GmailSettingsSharing,   //Manage your sensitive mail settings, including who can manage your mail
                                         GmailService.Scope.GmailSettingsBasic,     //Manage your basic mail settings                                 
                                         GmailService.Scope.GmailReadonly,          //View your emails messages and settings
                                         GmailService.Scope.GmailCompose,           //Manage drafts and send emails
                                         GmailService.Scope.GmailInsert,            //Insert mail into your mailbox
                                         GmailService.Scope.GmailLabels,            //Manage mailbox labels
                                         GmailService.Scope.GmailModify,            //View and modify but not delete your email
                                         GmailService.Scope.GmailSend,              //Send email on your behalf
                                         GmailService.Scope.MailGoogleCom};                             //View and manage your mail
        UserCredential credential;
        using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

            // Requesting Authentication or loading previously stored authentication for userName
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                     scopes,
                                                                     userName,
                                                                     CancellationToken.None,
                                                                     new FileDataStore(credPath, true)).Result;
        }

        // Create Drive API service.
        return new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Gmail Oauth2 Authentication Sample"
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine("Create Oauth2 account GmailService failed" + ex.Message);
        throw new Exception("CreateServiceAccountGmailFailed", ex);
    }
}

请求。

// find the label I want to use.
var findLabel = serviceGmail.Users.Labels.List("me").Execute().Labels.Where(a => a.Name.ToLower().Equals("daimto")).FirstOrDefault();

// search for the mails that I want to add it to
var request = serviceGmail.Users.Messages.List("me");
request.Q = "from:stuff@daimto.com";
request.Execute();

var allmails = request.Execute();           

ModifyMessageRequest mods = new ModifyMessageRequest();
mods.AddLabelIds = new List<string> { allLabels.Id };

// loop though each email.
foreach (var item in allmails.Messages)
   {
   var result = serviceGmail.Users.Messages.Modify(mods, "me", item.Id).Execute();
   }

我使用的是Gmail.dll 1.19.0.694,代码来自我的示例项目Google-dotnet-samples gmail v1