0
votes

I simply want to download attachments from my last emails programmatically with ASP.NET MVC.

As far as I can find here, the only permission I need from google is "https://www.googleapis.com/auth/gmail.readonly" that grants me "Read all resources and their metadata—no write operations." Source: (https://developers.google.com/gmail/api/auth/scopes )

The problem is when I try to access the attach I get an error:

$exception  
{"Google.Apis.Requests.RequestError
Invalid attachment token [400]
Errors 
[Message[Invalid attachment token] 
Location[ - ] Reason[invalidArgument] 
Domain[global]\r\n]\r\n"}

This is an example of my code, so far:

  static string[] Scopes = { GmailService.Scope.GmailReadonly };

   public ActionResult Login()
    {
        UserCredential credential;
        var diskPath = Server.MapPath("~");

        using (var stream = new FileStream(diskPath + "/Content/client_secret.json", FileMode.Open, FileAccess.Read))
        {
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None).Result;
        }

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

        var resp = service.HttpClient.GetStringAsync("https://www.googleapis.com/gmail/v1/users/me/messages?q=\"has:attachment\"").Result;
        var root = JsonConvert.DeserializeObject<ListMessagesResponse>(resp);
        foreach (var msg in root.Messages)
            GetAttachments(service, msg.Id);

        return View();
    }

    public static void GetAttachments(GmailService service, String messageId)
    {
        var message = service.Users.Messages.Get("me", messageId).Execute();
        var parts = message.Payload.Parts;
        foreach (var part in parts)
        {
            if (!String.IsNullOrEmpty(part.Filename))
            {
                var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();
                var file = Convert.FromBase64String(attachPart.Data);
                System.IO.File.WriteAllBytes(part.Filename, file);
            }
        }
    }

I get this error when I go through:

  var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();

Is there any other Scope I have to put in for Attachments? Or do I have to refresh the token after some operations? I already tried to remove and add again the App in my Google+ profile!

1

1 Answers

2
votes

[MY ERROR]

Instead of:

 var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();

I must use the ATTACHMENT ID like this:

 var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.Body.AttachmentId).Execute();