首页 > 解决方案 > Microsoft.Graph:如何设置大型嵌入式嵌入式附件/图像的 ContentId

问题描述

要使用 Microsoft.Graph 发送电子邮件,我使用如下代码(简化):

var recipientList = new List<Recipient>
{
    new Recipient { EmailAddress = new EmailAddress {Address = "recipient@example.com"}}
};

var email = new Message
{
    Body = new ItemBody
    {
        Content = "<html> ... <img src='cid:CID12345@example.com'> ... </html>",  
        ContentType = BodyType.Html,
    },
    Subject = "Message containing inline image",
    ToRecipients = recipientList,
};

Message draft = await graphClient.Me
.MailFolders
.Drafts
.Messages
.Request()
.AddAsync(email);


byte[] contentBytes = ...;

if (contentBytes.Length < 3 * 1024 * 1024)
{
    // Small Attachments

    var fileAttachment = new FileAttachment
    {
        Name = "Image.png",
        ContentBytes = contentBytes,
        ContentId = "CID12345@example.com",
        IsInline = true,
        Size = contentBytes.Length
    };

    Attachment uploadedFileAttachment = await graphClient.Me.Messages[draft.Id].Attachments
        .Request()
        .AddAsync(fileAttachment);
}
else
{
    // Large Attachments

    var contentStream = new MemoryStream(contentBytes);

    var attachmentItem = new AttachmentItem
    {
#warning TODO: How to set ContentId?

        AttachmentType = AttachmentType.File,
        Name = "Image.png",
        Size = contentStream.Length,
        IsInline = true,
    };

    UploadSession uploadSession = await graphClient.Me.Messages[draft.Id].Attachments
        .CreateUploadSession(attachmentItem)
        .Request()
        .PostAsync();

    var maxSliceSize = 320 * 1024;  // Must be a multiple of 320KiB.
    var largeFileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, contentStream, maxSliceSize);

    UploadResult<FileAttachment> uploadResult = await largeFileUploadTask.UploadAsync();

await graphClient.Me.Messages[draft.Id].Send().Request().PostAsync();
}

电子邮件包含内嵌图像。图像文件作为附件添加。为了将此附件链接到 HTML img 元素,我将 FileAttachment.ContentId 设置为我也在 HTML 图像元素的 src 属性中设置的值。

只要图像小于 3 MB,它就可以工作。对于较大的附件,我们必须以不同的方式添加附件 - 这也显示在上面的代码中。不使用 FileAttachment,而是使用 AttachmentItem,它具有类似于 FileAttachment 的 IsInline-Property。不幸的是,与 FileAttachment 不同,AttachmentItem 没有 ContentId 属性。

https://docs.microsoft.com/en-us/graph/api/resources/fileattachment?view=graph-rest-1.0 https://docs.microsoft.com/en-us/graph/api/resources/attachmentitem ?view=graph-rest-1.0

如何在大型附件上设置 ContentId?

标签: microsoft-graph-sdksmicrosoft-graph-mail

解决方案


我注意到在做大附件时,即使在 AttachmentItem 上设置 IsInline 为 true,在所有字节上传后,它仍然在附加到消息的 FileAttachment 项上设置为 false,并且内容 ID 为空...

您也不能使用附件 ID 来设置内容 ID 和 isInline 属性的附件补丁,因为您将获得该方法不允许异常/错误...

纵观这一切,我已经尽我所能尝试让大型附件图像能够用作内联图像,但我尝试过的任何事情都没有奏效。

我不知道为什么他们会将其限制为仅小于 3-4 MB 才能用作附件,但似乎他们已经硬限制了它并且无意允许这样做。如果有人能证明我错了,尽管我很想听听更多!


推荐阅读