简体   繁体   English

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

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


I want read all messages in my gmail account using c# and gmail api.我想使用 c# 和 gmail api 阅读我的 gmail 帐户中的所有邮件。
Can I do this?我可以这样做吗?
I read a lot of articles in Gmail API , but i couldn't read messages.我在Gmail API 中阅读了很多文章,但我无法阅读邮件。
Also I want to read a body of messages or header.我还想阅读消息正文或标题。
I will be very glad if someone can help me :)如果有人可以帮助我,我会很高兴:)

I use this code snippet:我使用这个代码片段:

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

And this:和这个:

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

But in a result I have empty message box.但结果我有空的消息框。

It works for me这个对我有用

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

Yes you should have no issue doing what you say.是的,你应该按照你说的去做。 I would suggest reading the documentation a bit more.我建议多阅读文档。

First you have to authenticate - the following shows how to do this with a service account (more details here https://developers.google.com/gmail/api/auth/web-server )首先,您必须进行身份验证 - 以下显示了如何使用服务帐户执行此操作(更多详细信息请访问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)
                         {}
                    } 

Once you have the message List you can iterate through the messages and either use a MIME parser or traverse the message structure to get the header, body etc.获得消息列表后,您可以遍历消息并使用 MIME 解析器或遍历消息结构以获取标题、正文等。

There are lots of posts in this forum which go through how to do that.这个论坛中有很多帖子介绍了如何做到这一点。

I searched for a full example, without luck, but this is my working example.我搜索了一个完整的示例,但运气不佳,但这是我的工作示例。 Based on https://developers.google.com/gmail/api/guides基于https://developers.google.com/gmail/api/guides

  1. Authenticate : https://developers.google.com/gmail/api/auth/web-server验证: https : //developers.google.com/gmail/api/auth/web-server
  2. get ALL emails获取所有电子邮件
  3. loop through all emails by Id, and request message etc.通过 Id 遍历所有电子邮件,并请求消息等。

here is the code snippet to get the first email's atachments, but you can simply loop over all foundIds to get all emails, and use message.snippet to get body :这是获取第一封电子邮件附件的代码片段,但您可以简单地遍历所有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);
            }

I would suggest taking a look at this article on how to handle the actual response structure.我建议看一下这篇关于如何处理实际响应结构的文章。 It can be somewhat complex with the way the Gmail API gives the results back to you. Gmail API 将结果返回给您的方式可能有些复杂。

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

@BlackCat, Your ListMessages looks good. @BlackCat,您的 ListMessages 看起来不错。 Now, to get the message body, you have to decode MimeType "text/plain" or "text/html".现在,要获取消息正文,您必须解码 MimeType "text/plain" 或 "text/html"。 For eg:例如:

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