如何从Gmail获取电子邮件附件元数据,而不是内容

本文关键字:元数据 Gmail 获取 电子邮件 | 更新日期: 2023-09-27 17:55:25

我只需要来自Gmail的附件的标题和元数据,我不想获取电子邮件正文或附件的内容,因为它们可能非常大,我不需要它们。

有没有办法通过AE做到这一点。Net.Mail 还是 gmail api?它似乎只有一个标题选项,它不会为我获取附件元数据。

MailMessage[] GetMessages(string startUID, string endUID, bool headersonly = true, bool setseen = false);

如何从Gmail获取电子邮件附件元数据,而不是内容

最终,我放弃了AE。Net.Mail并切换到Gmail API。并且我能够从消息获取请求中获取附件元数据,而无需获取实际的附件文件。

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

如果您使用 MailKit 而不是 AE。Net.Mail,您可以使用以下代码片段获取附件的元数据:

using (var client = new ImapClient ()) {
    client.Connect ("imap.gmail.com", 993, true);
    client.Authenticate ("username", "password");
    client.Inbox.Open (FolderAccess.ReadWrite);
    var summaries = client.Fetch (0, -1, MessageSummaryItems.UniqueId |
        MessageSummaryItems.BodyStructure | // metadata for mime parts
        MessageSummaryItems.Envelope);      // metadata for messages
    foreach (var summary in summaries) {
        // Each summary item will have the UniqueId, Body and Envelope properties
        // filled in (since that's what we asked for).
        var uid = summary.UniqueId.Value;
        Console.WriteLine ("The UID of the message is: {0}", uid);
        Console.WriteLine ("The Message-Id is: {0}", summary.Envelope.MessageId);
        Console.WriteLine ("The Subject is: {0}", summary.Envelope.Subject);
        // Note: there are many more properties, but you get the idea...
        // Since you want to know the metadata for each attachment, you can
        // now walk the MIME structure via the Body property and get
        // whatever details you want to get about each MIME part.
        var multipart = summary.Body as BodyPartMultipart;
        if (multipart != null) {
            foreach (var part in multipart.BodyParts) {
                var basic = part as BodyPartBasic;
                if (basic != null && basic.IsAttachment) {
                    // See http://www.mimekit.net/docs/html/Properties_T_MailKit_BodyPartBasic.htm
                    // for more details on what properties are available.
                    Console.WriteLine ("The size of this attachment is: {0} bytes", basic.Octets);
                    Console.WriteLine ("The file name is: {0}", basic.FileName);
                    // If you want to download just this attachment, you can download it like this:
                    var attachment = client.Inbox.GetBodyPart (uid, basic);
                }
            }
        }
    }
    client.Disconnect (true);
}

请记住,由于 MIME 是树结构而不是平面列表,因此您实际上希望以递归方式遍历多部分。