Gmail API .NET: Get full message

天大地大妈咪最大 提交于 2019-12-12 04:15:35

问题


How do I get the full message and not just the metadata using gmail api?

I have a service account and I am able to retrieve a message but only in the metadata, raw and minimal formats. How do I retrieve the full message in the full format? The following code works fine

var request = service.Users.Messages.Get(userId, messageId);
request.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Metadata;
Message message = request.Execute();

However, when I omit the format (hence I use the default format which is FULL) or I change the format to UsersResource.MessagesResource.GetRequest.FormatEnum.Full I get the error: Metadata scope doesn't allow format FULL

I have included the following scopes:

https://www.googleapis.com/auth/gmail.readonly, 
https://www.googleapis.com/auth/gmail.metadata,
https://www.googleapis.com/auth/gmail.modify,
https://mail.google.com/

How do I get the full message?


回答1:


I had to remove the scope for the metadata to be able to get the full message format.




回答2:


The user from the SO post have the same error.

Try this out first.

  1. Go to https://security.google.com/settings/security/permissions
  2. Choose the app you are working with.
  3. Click Remove > OK
  4. Next time, just request exactly which permissions you need.

Another thing, try to use gmailMessage.payload.parts[0].body.dataand to decode it into readable text, do the following from the SO post:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(gmailMessage.payload.parts[0].body.data)));

You can also check this for further reference.




回答3:


try something like this

    public String getMessage(string user_id, string message_id)
    {
         Message temp =service.Users.Messages.Get(user_id,message_id).Execute();
         var parts = temp.Payload.Parts;
         string s = "";
         foreach (var part in parts) {
                byte[] data = FromBase64ForUrlString(part.Body.Data);
                s += Encoding.UTF8.GetString(data);
         }
        return s
       }

    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());
        }


来源:https://stackoverflow.com/questions/45593958/gmail-api-net-get-full-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!