如何从发送到Google组邮件地址的电子邮件中下载附件

时间:2018-12-11 17:29:41

标签: c# .net gmail-api google-groups

假设我的电子邮件a@company.com在Google组中,该组的电子邮件地址为group@company.com。我们有一个g套件服务帐户,该帐户已启用Google Apps域范围内的委派。 我们有从b@companyb.com发送到我们的组电子邮件group@company.com的电子邮件,主题为Report from company b并将报告附加在电子邮件中。

问题是gmail api能够列出所有邮件,但不能列出每封电子邮件中的附件。

有什么办法吗?

这是我的代码:

    // here when I create the client, I use my email address `a@company.com`
    using(var client = CreateClient())
    {
        UsersResource.MessagesResource.ListRequest request = client.Users.Messages.List("me");

        request.Q = "from:b@compayb.com AND subject:Report from company b AND has:attachment"

        // List messages.
        var messageIds = request.Execute().Messages?.Select(m => m.Id) ?? new List<string>();

        foreach(var mId in messageIds)
        {
            // https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get
            Message message = client.Users.Messages.Get("me", messageId).Execute();
            IList<MessagePart> parts = message.Payload.Parts;
            foreach (MessagePart part in parts)
            {
                if (!String.IsNullOrEmpty(part.Filename))
                {
                    String attId = part.Body.AttachmentId;
                    MessagePartBody attachPart = client.Users.Messages.Attachments.Get("me", messageId, 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);
                    var file = new FileInfo(part.Filename);
                    File.WriteAllBytes(file.FullName, data);
                }
            }
        }
    }

如果我手动将邮件转发到相同的地址(因此收件人将为me),则代码将下载附件。

如果能提供帮助,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

我发现附件位于子MessagePart中。因此,我编写了递归方法来遍历所有部件以获取所有附件。

    // List<FileInfo> Files = new List<FileInfo>();
    // client is created outside this method
    private void GetAttachmentsFromParts(IList<MessagePart> parts, string messageId)
    {
        if (parts == null) return;

        foreach (MessagePart part in parts)
        {
            if (!String.IsNullOrEmpty(part.Filename))
            {
                String attId = part.Body?.AttachmentId ?? null;
                if(String.IsNullOrWhiteSpace(attId)) continue;

                MessagePartBody attachPart = GmailServiceClient.Users.Messages.Attachments.Get("me", messageId, 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);
                var file = new FileInfo(part.Filename);
                Files.Add(file);
                File.WriteAllBytes(file.FullName, data);
            }

            if((part.Parts?.Count ?? 0) > 0)
                GetAttachmentsFromParts(part.Parts, messageId);
        }
    }

所有附件将存储在List<FileInfo> Files