How to send MIMECONTENT using Graph SDK V5 (.NET)

박동혁 0 Reputation points
2024-04-05T06:08:06.4166667+00:00

Currently, I'm working on sending reserved mail system using graph sdk.

I'm trying to send saved .eml file(Mimecontent) using graph sdk (v5).

I found some way on https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=http but it only show way for http.

Therefore, I'm using MIMEKIT library and reconstruct the email and send but I don't think this is a best way to do it.

byte[] newbuffer = File.ReadAllBytes(filepath);
using (var memoryStream = new MemoryStream(newbuffer)) {
    var mimeMessage = MimeKit.MimeMessage.Load(memoryStream);
    var message = new Microsoft.Graph.Models.Message
    {
        Subject = mimeMessage.Subject,
        Body = new Microsoft.Graph.Models.ItemBody
        {
            ContentType = mimeMessage.HtmlBody != null ? Microsoft.Graph.Models.BodyType.Html : Microsoft.Graph.Models.BodyType.Text,
            Content = mimeMessage.HtmlBody ?? mimeMessage.TextBody
        },
        ToRecipients = mimeMessage.To.Mailboxes.Select(mailbox => new Microsoft.Graph.Models.Recipient
        {
            EmailAddress = new Microsoft.Graph.Models.EmailAddress { Address = mailbox.Address }
        }).ToList()
    };
    var draftMessage = await gsc.Users[userinfo.UserPrincipalName].Messages.PostAsync(message);
    foreach (var attachment in mimeMessage.Attachments.OfType<MimeKit.MimePart>())
    {
        var attachmentStream = new MemoryStream();
        attachment.Content.DecodeTo(attachmentStream);
        byte[] fileBytes = attachmentStream.ToArray(); 
        attachmentStream.Dispose(); 
        var fileAttachment = new Microsoft.Graph.Models.FileAttachment
        {
            OdataType = "#microsoft.graph.fileAttachment",
            ContentBytes = fileBytes,
            ContentType = attachment.ContentType.MimeType,
            Name = attachment.FileName
        };
        await gsc.Users[userinfo.UserPrincipalName].Messages[draftMessage.Id].Attachments.PostAsync(fileAttachment);
    }
    await gsc.Users[userinfo.UserPrincipalName].Messages[draftMessage.Id].Send.PostAsync();
}

I'm wondering I may use ToPostRequestInformation for more simple way? Or anyone know the other way? please help me

Thanks

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,020 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.