I followed these 2 links to create a console app for sending emails using Graph API:
https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=csharp
Microsoft Graph API unable to Send Email C# Console
I have added & granted the required permissions in Azure AD app:
I made sure to provide the client id, tenant id, client secret.
However, I see this error on running the console:
What am I missing?
Here is the code I tried from Microsoft Graph API unable to Send Email C# Console
static void Main(string[] args)
{
// Azure AD APP
string clientId = "<client Key Here>";
string tenantID = "<tenant key here>";
string clientSecret = "<client secret here>";
Task<GraphServiceClient> callTask = Task.Run(() => SendEmail(clientId, tenantID, clientSecret));
// Wait for it to finish
callTask.Wait();
// Get the result
var astr = callTask;
}
public static async Task<GraphServiceClient> SendEmail(string clientId, string tenantID, string clientSecret)
{
var confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantID)
.WithClientSecret(clientSecret)
.Build();
var authProvider = new ClientCredentialProvider(confidentialClientApplication);
var graphClient = new GraphServiceClient(authProvider);
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 = "[email protected]"
}
}
},
CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "[email protected]"
}
}
}
};
var saveToSentItems = true;
await graphClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync();
return graphClient;
}
Based on your code which generates the confidentialClientApplication
, you are using Client credentials provider.
But the way you send the email is:
await graphClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync()
It is calling https://graph.microsoft.com/v1.0/me/sendMail
in fact.
But Client credentials flow doesn't support /me
endpoint. You should call https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/sendMail
endpoint in this case.
So the code should be:
await graphClient.Users["{id or userPrincipalName}"]
.SendMail(message, saveToSentItems)
.Request()
.PostAsync();
Or if you want to use /me/sendMail
, choose Authorization code provider, where you should implement interactive login.
You can learn about the scenarios and differences between authorization code flow and client credentials flow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With