Search code examples
emailasp.net-core-mvcmicrosoft-graph-apiemail-attachments

Sending email using Microsoft graph with attachment. Microsoft code example unclear


HI I am trying to use Microsoft graph api to send messages.
Previously, I was sending messages/emails with the graph api without attachment. Now I need to attach 10 attachment each.

So I looked for examples and got to the Microsoft document and it shows the following code

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var attachment = new FileAttachment
{
 Name = "smile",
 ContentBytes = Convert.FromBase64String("R0lGODdhEAYEAA7")
};

await graphClient.Me.Messages["{message-id}"].Attachments
.Request()
.AddAsync(attachment);

Link: https://learn.microsoft.com/en-us/graph/api/message-post-attachments?view=graph-rest-1.0&tabs=csharp

My question is what it is showing is not clear I am not sure I would I use message-id. Also I dont see if the Message is created and how the attachment is created.

Can someone help please.


Solution

  • You may refer to this document to learn the example about how to send email with attachments. And the below is my test code, it worked for me, I used client credential flow to provide authentication..

    using Azure.Identity;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Graph;
    
    public class HomeController : Controller
    {
        private readonly IWebHostEnvironment _appEnvironment;
    
        public HomeController(IWebHostEnvironment appEnvironment)
        {
            _appEnvironment = appEnvironment;
        }
    
        public async Task<string> sendMailAsync() {
            var scopes = new[] { "https://graph.microsoft.com/.default" };
            var tenantId = "your_tenant_name.onmicrosoft.com";
            var clientId = "azure_ad_clientid";
            var clientSecret = "client_secret";
            var clientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret);
            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
            
            var a = _appEnvironment.WebRootPath;//I have a file stored in my project
            var file = a + "\\hellow.txt";
            byte[] fileArray = System.IO.File.ReadAllBytes(@file);
            //string base64string = Convert.ToBase64String(fileArray);
    
            var message = new Message
            {
                Subject = "Meet for lunch?",
                Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = "The new cafeteria is open."
                },
                ToRecipients = new List<Recipient>()
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = "xxx@outlook.com"
                        }
                    }
                },
                Attachments = new MessageAttachmentsCollectionPage()
                {
                    new FileAttachment
                    {
                        Name = "attachment.txt",
                        ContentType = "text/plain",
                        ContentBytes = fileArray
                    }
                }
            };
    
            await graphClient.Users["user_id"]
                .SendMail(message, null)
                .Request()
                .PostAsync();
    
            return "success";
        }
    }
    

    enter image description here enter image description here