1

最近微软宣布可以发送带有大于 4MB 附件的电子邮件。根据文档,我们必须创建草稿,然后是上传会话,上传附件,最后发送邮件。

我可以使用以下代码创建草稿:

var confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithClientSecret(clientSecret)
    .WithTenantId(tenant)
    .Build();

var authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);
var graphClient = new GraphServiceClient(authenticationProvider);

var email = new Message
{
    Body = new ItemBody
    {
      Content = i + " Works fine! " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
      ContentType = BodyType.Html,
    },
    Subject = "Test" + (j == 0 ? "" : " " + j),
    ToRecipients = recipientList,
    Attachments = att
};

Message draft = await graphClient
    .Users["test@test.onmicrosoft.com"]
    .Messages
    .Request()
    .AddAsync(mail);

但是当我尝试从文档中提取片段时:

var attachmentItem = new AttachmentItem
{
    AttachmentType = AttachmentType.File,
    Name = "flower",
    Size = 3483322
};

await graphClient.Me.Messages["AAMkADI5MAAIT3drCAAA="].Attachments
    .CreateUploadSession(attachmentItem)
    .Request()
    .PostAsync();

我得到这些错误:

  1. 找不到类型或命名空间名称“AttachmentItem”(您是否缺少 using 指令或程序集引用?)
  2. 当前上下文中不存在名称“AttachmentType”
  3. “IMessageAttachmentsCollectionRequestBuilder”不包含“CreateUploadSession”的定义,并且找不到接受“IMessageAttachmentsCollectionRequestBuilder”类型的第一个参数的可访问扩展方法“CreateUploadSession”(您是否缺少 using 指令或程序集引用?)

我添加了对稳定版和 beta 版图形库(Microsoft.Graph、Microsoft.Graph.Beta)的引用(我之前使用过 beta 端点),但我找不到AttachmentItem.

我已经搜索了 AttachmentItem 的两个存储库(https://github.com/microsoftgraph/msgraph-sdk-dotnethttps://github.com/microsoftgraph/msgraph-beta-sdk-dotnet),但我什么也没找到.

发送带有大附件的邮件是一项相当新的功能(文档来自 2019 年 10 月 25 日),但根据文档,这应该得到支持。

文档错了吗?如何创建上传会话并上传附件?我必须手动创建请求吗?或者我可以使用 Microsoft.Graph 库吗?

我只看到CreateUploadSessionDrive - https://github.com/microsoftgraph/msgraph-sdk-dotnet/search?q=CreateUploadSession&unscoped_q=CreateUploadSession

4

2 回答 2

2

我不得不四处寻找可行的解决方案。请注意,此示例使用在撰写本文时仍处于预览阶段的 Microsoft.Graph.Auth nuget,因此它可能会在以后进一步更改。

var tenant = "xxxxxxxxxxxxxxxxxx";
var client = "yyyyyyyyyyyyyyyyyy";
var secret = "xxxxxxxxxxxxxxxxxx";
var senderEmail = "user_email@yourdomainato365.com";

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(client)
    .WithTenantId(tenant)
    .WithClientSecret(secret)
    .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider );

var fileName = "some_huge_file.pdf";
var path = System.IO.Path.Combine(@"D:\Path_To_Your_Files", fileName );
var message = new Message
{
    Subject = "Check out this Attachment?",
    Body = new ItemBody
    {
        ContentType = BodyType.Html,
        Content = "Its <b>awesome</b>!"
    },
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "john_doe@gmail.com"
            }
        }
    },
};

var attachmentContentSize = new System.IO.FileInfo(path).Length;

//check to make sure content is below 3mb limit
var isOver3mb = attachmentContentSize > (1024*1024*3);

//if below our limit, send directly.
if( isOver3mb == false )
{
    message.Attachments = new MessageAttachmentsCollectionPage()
    {
        new FileAttachment{ Name = fileName, ContentBytes = System.IO.File.ReadAllBytes(path) }     
    };
    
    await graphClient.Users[senderEmail].SendMail(message, true).Request().PostAsync();
}
else
{
    //first create an email draft
    var msgResult = await graphClient.Users[senderEmail].Messages
                            .Request()
                            .AddAsync(message);

    var attachmentItem = new AttachmentItem
    {
        AttachmentType = AttachmentType.File,
        Name = fileName,
        Size = attachmentContentSize,       
    };

    //initiate the upload session for large files (note that this example doesn't handle multiple attachment).
    var uploadSession = await graphClient.Users[senderEmail].Messages[msgResult.Id].Attachments
                                                            .CreateUploadSession(attachmentItem)
                                                            .Request()
                                                            .PostAsync();
     
    var maxChunkSize = 1024 * 320;      
    var allBytes = System.IO.File.ReadAllBytes(path);
        
    using( var stream =  new MemoryStream ( allBytes ) )
    {
        stream.Position = 0;
        LargeFileUploadTask<FileAttachment> largeFileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, stream, maxChunkSize);

        await largeFileUploadTask.UploadAsync();
    }
    //once uploaded, sends out the email from the Draft folder
    await graphClient.Users[senderEmail].Messages[msgResult.Id].Send().Request().PostAsync();
}
于 2021-03-30T02:43:49.730 回答
0

此功能处于预览版(又名 Beta)中。由于这些 API 和资源仅存在于 Graph Beta 中,因此您无法使用 GA 版本的Microsoft.Graph库。您需要使用库的Microsoft.Graph.Beta版本。

于 2019-11-07T14:36:54.540 回答