Graph 获取带有 PDF 附件的电子邮件并下载

问题描述 投票:0回答:1

我一整天都在努力解决这个问题,并且已经解决了这里的大部分问题。无法让它工作 我知道被提取的电子邮件有 PDF 附件,但是当我运行代码时,我没有得到任何被提取的东西。事实上,附件对象通常显示为 NULL,但是 HasAttachments 返回 true 并给了我一个 URL。有人有什么想法吗?

int i = 0;
var msgs = _graphServiceClient.Users["[email protected] "].Messages.Request().Filter("(from/emailAddress/address) eq '[email protected]'").Top(5000).Header("Prefer", "outlook.body-content-type='text'").GetAsync().Result;
foreach (var message in msgs) //.Where(a => a.Subject.Contains("Defense reminder notifications")))
{

    var mesAtt = _graphServiceClient.Users["[email protected]"].Messages[message.Id].Request().Expand("Attachments").GetAsync();
    
    if (message.HasAttachments == true && message.Attachments != null) { 
        var fileAttachment = message.Attachments.OfType<FileAttachment>().FirstOrDefault(a => a.ContentId == "application/pdf");

    int b = 0;
    if (fileAttachment != null)
    {
        var base64 = fileAttachment.ContentBytes;
        System.IO.FileStream stream = new FileStream(@"C:\TMP\" + b + "file.pdf", FileMode.CreateNew);
        System.IO.BinaryWriter writer =
        new BinaryWriter(stream);
        writer.Write(base64, 0, base64.Length);
        writer.Close();
     }
     b++;
} 
c# microsoft-graph-api email-attachments microsoft-graph-mail
1个回答
0
投票
    if (message.HasAttachments == true && message.Attachments != null) { 
    var fileAttachment = message.Attachments.OfType<FileAttachment>().FirstOrDefault(a => a.ContentId == "application/pdf");

这对我来说看起来不正确你永远不应该在 contentId 中有 application/pdf 这应该是一个唯一的值并且通常是一个 Guid。我建议您先在 Graph Explorer 中尝试展开带有附件的邮件,然后查看结果。您可能会看到 application/pdf 的唯一地方是在 contentType 和/或 mediaContentType 中,但这也不能保证,并且可能是 application/octet-stream,具体取决于原始编码器。例如这是一个例子

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('-8cf15854b555')/messages(attachments,attachments())/$entity",
    "@odata.etag": "W/\"CQAAABYAAAB1EEf9GOowTZ1AsUKLrCDQAAejSsO4\"",
    "id": "ASAAA=",
    "attachments": [
        {
            "@odata.type": "#microsoft.graph.fileAttachment",
            "@odata.mediaContentType": "application/pdf",
            "id": "AAMkADczNDE4YWEwLTdlZmItNDIzZC04MDViLTYyYjI2YmRhYzI2ZABGAAAAAAC_HN09lgYnSJDz3kt9375JBwB1EEf9GOowTZ1AsUKLrCDQAAAAAAEMAAB1EEf9GOowTZ1AsUKLrCDQAAek6VdSAAABEgAQAKqtypyRZE1Jg0YRo9yWihE=",
            "lastModifiedDateTime": "2023-03-27T03:17:31Z",
            "name": "62104645031_000347650792_P_20230327.pdf",
            "contentType": "application/pdf",
            "size": 166611,
            "isInline": false,
            "contentId": "[email protected]",
            "contentLocation": null,
            "contentBytes":""
        }
}

最通用/最可靠的方法就是检查名称中的 .pdf 扩展名。

也不做

Top(5000)  

Graph 会将您限制在一个页面中最多 1000 个项目,如果您想要处理分页结果所需的项目数量,这可能会使其他开发人员感到困惑。

© www.soinside.com 2019 - 2024. All rights reserved.