Gmail API阅读邮件

时间:2017-07-14 17:01:48

标签: c# gmail-api

我正在尝试使用gmail api阅读电子邮件。但身体信息的格式是不可读的。

static void Main(string[] args)
    {
        UserCredential credential;

        using (var stream =
            new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

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


        UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");
        IList<Message> messages = request.Execute().Messages;
        if (messages != null && messages.Count > 0)
        {
            foreach (var messageItem in messages)
            {
                var readMessage = service.Users.Messages.Get("me", messageItem.Id).Execute();
                var body = readMessage.Payload.Parts[0].Body.Data;
            }
        } }

当我调试我的测试应用程序时,body变量得到值:

        body    "DQpLaW5kIFJlZ2FyZHMsDQoNCldpbGwNCg0KV2lsbCBLZWx0eQ0KMzIzLjI1Mi44Njk5DQp3a2VsdHlAZ21haWwuY29tIDxtYWlsdG86d2tlbHR5QGdtYWlsLmNvbT4NCmh0dHBzOi8vd3d3LmZhY2Vib29rLmNvbS9iaWdibHVlZG93bnRvd24gPGh0dHBzOi8vd3d3LmZhY2Vib29rLmNvbS9iaWdibHVlZG93bnRvd24-DQp3d3cubWV0cm9saWZlcHJvcGVydGllcy5jb20gPGh0dHA6Ly93d3cubWV0cm9saWZlcHJvcGVydGllcy5jb20vPg0KDQpCZWdpbiBmb3J3YXJkZWQgbWVzc2FnZToNCg0KRnJvbTogIkNSRVhpIiA8bm90aWZpY2F0aW9uc0BjcmV4aS5jb20-DQpTdWJqZWN0OiB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UjhEWEZndzh1WGZMSFdNUmc0R2Y2MWMwb2JNUEQtMkI4c1QtMkJ1NTFtRj4JDQogDQogPGh0dHA6Ly9lbWFpbC1saW5rcy5jcmV4aS5jb20vd2YvY2xpY2s_dXBuPVVnWW9yUXo0"  string

有谁知道为什么?

由于

3 个答案:

答案 0 :(得分:5)

更改此行

var body = readMessage.Payload.Parts[0].Body.Data;

var body = Base64UrlDecode(readMessage.Payload.Parts[0].Body.Data);

在代码中添加此方法:

public static string Base64UrlDecode(string input)
{
    if (string.IsNullOrWhiteSpace(input))
        return "<strong>Message body was not returned from Google</strong>";

    string InputStr = input.Replace("-", "+").Replace("_", "/");
    return System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(InputStr));

}

此外,要处理多部分而不返回多部分,您可以使用以下代码:

if (ml.Payload.Parts != null) {
    foreach (void bParts_loopVariable in ml.Payload.Parts) {
        bParts = bParts_loopVariable;
        if (bParts.MimeType == "text/html") {
            if (bParts.Body != null) {
                dynamic mp = bParts.Body;
                if (mp != null) {
                    return Base64UrlDecode(mp.Data);

                }
            }
        }
    }
} else {
    return Base64UrlDecode(ml.Payload.Body.Data);
}

答案 1 :(得分:0)

正文是Base64编码的。

您需要调用Convert.FromBase64String(string)来获取纯文本。

答案 2 :(得分:0)

您应该使用readMessage.GetRaw()方法。请参阅下文如何解码base64字符串:

byte[] data = Convert.FromBase64String(readMessage.GetRaw());
string messageString = Encoding.UTF8.GetString(data);

参见ref https://developers.google.com/gmail/api/v1/reference/users/messages/get