I'm trying to send an email from a c# console application. I've created an azure app and have the clientId and Clientsecret
Trying to send a mail with the following code throws the ODataError with message in title. Any idea?
public static async Task SendAsync(string toAddress, string subject, string content)
{
string? tenantName = "[email protected]";
string? tenantId = "xx";
string? clientId = "xx";
string? clientSecret = "xx";
//string[] scopes = new string[] { "user.read", "Mail.Send" };
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
ClientSecretCredential credential = new(tenantId,
clientId,
clientSecret,
new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud });
var graphServiceClient = new GraphServiceClient(credential, scopes);
var requestBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody
{
Message = new()
{
Subject = subject,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = content
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = toAddress
}
}
},
},
SaveToSentItems = true,
};
try
{
await graphServiceClient.Users[tenantName].SendMail.PostAsync(requestBody);
}
catch (Microsoft.Graph.Models.ODataErrors.ODataError ex)
{
Console.WriteLine(ex.Message);
}
}
I agree with @DarkBee, the error usually occurs if the user does not have an active Office 365 license assigned.
Initially, I too got same error when I tried to send mail from user having no valid license:
To resolve the error, make sure to assign one active Office 365 license to the user:
When I ran below code after assigning license to the user, I got response like this:
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Models.ODataErrors;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var user = "[email protected]";
var clientId = "appId";
var tenantId = "tenantId";
var clientSecret = "secret";
var options = new ClientSecretCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var requestBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody
{
Message = new Message
{
Subject = "Send mail - Demo purpose",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Hi! This is Sri",
},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "[email protected]",
},
},
},
},
SaveToSentItems = true,
};
try
{
await graphClient.Users[user].SendMail.PostAsync(requestBody);
Console.WriteLine("Successfully sent mail");
}
catch (ODataError odataError)
{
Console.WriteLine(odataError.Error.Message);
}
Response:
To confirm that, I checked the same in user's Sent Items
where mail sent successfully as below: