2

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.

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
Jashvita
  • 553
  • 3
  • 24

1 Answers1

2

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

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
  • Thanks it did work for the text file but when I attach xlsx file. The file get attached to the email but when user open the email attachment for xlsx file. The error occurred as " excel cannot open the file because the file format or file extension is not valid " I even tried with the content type = application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. The issue remained. – Jashvita Apr 19 '22 at 10:39
  • I test in my side again and it worked for me. I just put an excel file in the wwwroot folder, then change to use `var file = a + "\\testExcel.xlsx";` and `new FileAttachment{ Name = "test.xlsx",ContentType = "text/plain",ContentBytes = fileArray }`. Just changing a file name. And in my excel file, I only entered "hello world" – Tiny Wang Apr 20 '22 at 01:33
  • thanks for your support but I am still getting the error after changing the whole code and copied yours. Text file or MS file are seem to work fine. – Jashvita Apr 21 '22 at 05:19
  • Since my original question was not related to the excel file but to attach the files to the Microsoft Graph Message which you answered and it did help me I am going to accept your answer. I will post a new question. Thanks – Jashvita Apr 21 '22 at 05:21
  • in my code this `graphClient.Users["user_id"].SendMail` does not work – T.S. Mar 14 '23 at 03:10
  • @T.S. any error messages? api permission/authorization flow/user license(user should had license so that it can send email and by default user doesn't have a license)/SDK usage, these are the places which usually had issue. – Tiny Wang Mar 14 '23 at 03:21
  • @TinyWang Sorry, I wasn't clear. It does not like `SendMail(x,y)`. It tells me that `SendMail` is a property of `UserItemRequestBuilder`. But I use it as method. "Non-invokable member" – T.S. Mar 14 '23 at 03:27
  • I'm sorry that I can't understand your situation now. could you pls raise a new question in `microsoft-graph-api` tag with more details about your code and issue? I trust some other contributors like @user2250152 will help. – Tiny Wang Mar 14 '23 at 05:22
  • 1
    There is a change on how to call SendMail. Please see this https://stackoverflow.com/questions/70771954/how-to-send-email-from-any-one-email-using-microsoft-graph – aravind Apr 10 '23 at 18:42