简体   繁体   中英

Send email with large attachments using MS Graph library

Recently Microsoft announced that it is possible to send emails with attachments larger than 4MB. According to the docs, we must create a draft, then an upload session, upload attachment and finally send the mail.

I am able to create a draft using below code:

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);

but when I try snippet from the docs:

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

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

I get those errors:

  1. The type or namespace name 'AttachmentItem' could not be found (are you missing a using directive or an assembly reference?)
  2. The name 'AttachmentType' does not exist in the current context
  3. 'IMessageAttachmentsCollectionRequestBuilder' does not contain a definition for 'CreateUploadSession' and no accessible extension method 'CreateUploadSession' accepting a first argument of type 'IMessageAttachmentsCollectionRequestBuilder' could be found (are you missing a using directive or an assembly reference?)

I've added references to both stable and the beta version of graph libraries (Microsoft.Graph, Microsoft.Graph.Beta) (I used beta endpoint before) but I can't find AttachmentItem .

I've searched two repos ( https://github.com/microsoftgraph/msgraph-sdk-dotnet , https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet ) for AttachmentItem but I didn't find anything.

Sending mails with large attachments is quite a new feature (docs are from 25 October 2019), but according to docs this should be supported.

Are the docs wrong? How can I create an upload session and upload attachments? Must I create requests manually? Or can I use Microsoft.Graph library?

I only see CreateUploadSession for Drive - https://github.com/microsoftgraph/msgraph-sdk-dotnet/search?q=CreateUploadSession&unscoped_q=CreateUploadSession

I had to search around for a working solution. Note that this sample uses the Microsoft.Graph.Auth nuget that is still under preview at the time of this writing, hence it may be subjected to change further down the line.

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();
}

This functionality is in Preview (aka Beta). Since these APIs and resources only exist in the Graph Beta, you cannot use the GA version of the Microsoft.Graph library. You need to use the Microsoft.Graph.Beta version of the library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM