繁体   English   中英

我可以使用 gmail api 和 c# 读取来自 gmail 的邮件吗?

[英]Can I read messages from gmail using gmail api and c#?


我想使用 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);

但结果我有空的消息框。

这个对我有用

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

是的,你应该按照你说的去做。 我建议多阅读文档。

首先,您必须进行身份验证 - 以下显示了如何使用服务帐户执行此操作(更多详细信息请访问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 解析器或遍历消息结构以获取标题、正文等。

这个论坛中有很多帖子介绍了如何做到这一点。

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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM