I'm using C# Microsoft Graph to send an email but I'm facing the error "Object reference not set to an instance of an object" when I call the await graphClient.Me.SendMail(message).Request().PostAsync() method. I tried to call var request = graphClient.Me.SendMail(message).Request() first and see that the request object is not null but when I call request.PostAsync() it gives the error, so I think PostAsync() method has a problem or I am missing something.
I'm not sure that if we can use the access token from msal-browser to send an email in C#?
Here is the code workflow:
- On the browser I call msalInstance.loginPopup(loginRequest) method to get accesstoken after user selects their outlook account.
- Then I send the accesstoken from the client to the backend to send an email. But I'm facing the error at this step await graphClient.Me.SendMail(message).Request().PostAsync();
Notes: I want to send an email from the backend (C#) instead of javascript because I want to handle some logic code at the backend.
Then you need to modify your send email method like this, it worked for me:
public async Task sendAsync() {
var mesg = 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 = "[email protected]"
}
}
},
Attachments = new MessageAttachmentsCollectionPage()
};
var temp = new MailContentModel
{
message = mesg
};
var jsonStr = JsonSerializer.Serialize(temp);
string token = "your_token";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await httpClient.PostAsync("https://graph.microsoft.com/v1.0/me/sendMail", new StringContent(jsonStr, Encoding.UTF8, "application/json"));
}
using Microsoft.Graph;
public class MailContentModel
{
public Message message { get; set; }
}

