我可以使用gmail api和c#从gmail中读取消息吗?

时间:2015-02-15 15:30:28

标签: c# gmail gmail-api


我希望使用c#和gmail api读取我的Gmail帐户中的所有邮件。
我可以这样做吗? 我在Gmail API阅读了很多文章,但我无法阅读邮件 另外,我想阅读一些消息或标题。
如果有人可以帮助我,我会很高兴:)

我使用此代码段:

public static List<Message> ListMessages(GmailService service, String userId)
    {
        List<Message> result = new List<Message>();
        UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);

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

        return result;
    }

而且:

foreach (var item in ListMessages(service,"me"))
                MessageBox.Show(item.Snippet);

但结果我有空信息框。

5 个答案:

答案 0 :(得分:2)

对我有用

 var inboxlistRequest = service.Users.Messages.List("your-email-address");
 inboxlistRequest.LabelIds = "INBOX";
 inboxlistRequest.IncludeSpamTrash = false;
 //get our emails   
 var emailListResponse = inboxlistRequest.Execute();
 foreach (var mail in emailListResponse.Messages)
 {
       var mailId = mail.Id;
       var threadId = mail.ThreadId;

       Message message = service.Users.Messages.Get("your-email-address", mailId).Execute();
       Console.WriteLine(message.Snippet);
 }

答案 1 :(得分:0)

是的,按照你的说法你应该没有问题。我建议多阅读一下文档。

首先您必须进行身份验证 - 以下显示如何使用服务帐户执行此操作(此处更多详细信息https://developers.google.com/gmail/api/auth/web-server

                    serviceAccountEmail = primaryLink.serviceEmailAddress;
                    certificate = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "certs//" + primaryLink.certificate, primaryLink.certificatePassword, X509KeyStorageFlags.Exportable);

                    try
                    {
                        credential = new ServiceAccountCredential(
                        new ServiceAccountCredential.Initializer(serviceAccountEmail)
                        {
                            User = z.us.emailAccount,
                            Scopes = new[] { "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "https://mail.google.com/" }
                        }.FromCertificate(certificate));

                        if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
                        {
                            gs = new GmailService(
                            new Google.Apis.Services.BaseClientService.Initializer()
                            {
                                ApplicationName = "Example",
                                HttpClientInitializer = credential
                            });
                        }
                        else
                        {
                            throw new Exception("gmail authentication Error.");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    ListMessagesResponse respM = reqM.Execute();
                    if (respM.Messages != null)
                    {   
                         foreach (Message m in respM.Messages)
                         {}
                    } 

获得消息列表后,您可以遍历消息并使用MIME解析器或遍历消息结构以获取标题,正文等。

此论坛中有很多帖子都会介绍如何做到这一点。

答案 2 :(得分:0)

我没有运气就搜索了一个完整的示例,但这是我的工作示例。基于https://developers.google.com/gmail/api/guides

  1. 验证:https://developers.google.com/gmail/api/auth/web-server
  2. 获取 ALL 电子邮件
  3. 按ID遍历所有电子邮件,并请求消息等。

这是获取第一封电子邮件的代码段,但是您可以简单地遍历所有 foundIds 以获取所有电子邮件,并使用 message.snippet 获取正文:

            List<string> foundIds = new List<string>();
            string outputDir = "/EXAMPLE/EXAMPLE/"; // your preferred Dir to save attachments to



            List<Google.Apis.Gmail.v1.Data.Thread> resultThread = new List<Google.Apis.Gmail.v1.Data.Thread>();
            UsersResource.ThreadsResource.ListRequest requestThread = service.Users.Threads.List("me");


            do
            {
                try
                {
                    ListThreadsResponse responseThread = requestThread.Execute();
                    resultThread.AddRange(responseThread.Threads);

                    foreach (var item in responseThread.Threads )
                    {
                        foundIds.Add(item.Id);
                    }

                    requestThread.PageToken = responseThread.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                }
            } while (!String.IsNullOrEmpty(requestThread.PageToken));

            try
            {
                Message message = service.Users.Messages.Get("me", foundIds[0]).Execute();
                IList<MessagePart> parts = message.Payload.Parts;
                foreach (MessagePart part in parts)
                {
                    if (!String.IsNullOrEmpty(part.Filename))
                    {
                        String attId = part.Body.AttachmentId;
                        MessagePartBody attachPart = service.Users.Messages.Attachments.Get("me", foundIds[0], attId).Execute();

                        // Converting from RFC 4648 base64 to base64url encoding
                        // see http://en.wikipedia.org/wiki/Base64#Implementations_and_history
                        String attachData = attachPart.Data.Replace('-', '+');
                        attachData = attachData.Replace('_', '/');

                        byte[] data = Convert.FromBase64String(attachData);
                        File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }

答案 3 :(得分:0)

我建议您看一下这篇关于如何处理实际响应结构的文章。 Gmail API将结果返回给您的方式可能有些复杂。

https://sigparser.com/developers/email-parsing/gmail-api/

答案 4 :(得分:-1)

@BlackCat,你的ListMessages看起来不错。现在,要获取消息体,您必须解码MimeType“text / plain”或“text / html”。例如:

public static void GetBody(GmailService service, String userId, String messageId, String outputDir)
    {
        try
        {
            Message message = service.Users.Messages.Get(userId, messageId).Execute();
            Console.WriteLine(message.InternalDate);
            if (message.Payload.MimeType == "text/plain")
            {
                byte[] data = FromBase64ForUrlString(message.Payload.Body.Data);
                string decodedString = Encoding.UTF8.GetString(data);
                Console.WriteLine(decodedString);
            }
            else
            {
                IList<MessagePart> parts = message.Payload.Parts;
                if (parts != null && parts.Count > 0)
                {
                    foreach (MessagePart part in parts)
                    {
                        if (part.MimeType == "text/html")
                        {
                            byte[] data = FromBase64ForUrlString(part.Body.Data);
                            string decodedString = Encoding.UTF8.GetString(data);
                            Console.WriteLine(decodedString);
                        }
                    }
                }
            }
            Console.WriteLine("----");
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: " + e.Message);
        }
    }