It's possible that the permissions have not been granted. There is a different workflow for user-based authentication vs. application-based authentication. Make sure you have read/write permissions at the Application level in Azure AD portal.
Send mails using graph API is not working
Hi,
We have used the below code to sending emails using Graph API. but the below code works if i created a sample page and using async method.
But If I use the same code in my web application for sending emails it will be stuck in the below code.
await graphClient.Users["Graph user ID"]
.SendMail(message, false)
.Request()
.PostAsync();
Below is the function used for send emails.
public static async System.Threading.Tasks.Task SendMail(string MailSubject, string MailBody, string toID, string Cc)
{
var clientID = ConfigurationManager.AppSettings["ida:ClientId"];
var tenantID = ConfigurationManager.AppSettings["ida:TenantId"];
var secret = ConfigurationManager.AppSettings["ida:AppKey1"];
string authority = $"https://login.microsoftonline.com/{tenantID}/v2.0";
var scopesArr = new string[] { "https://graph.microsoft.com/.default" };
var confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientID)
.WithTenantId(tenantID)
.WithClientSecret(secret)
.Build();
GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
try
{
var authResult = await confidentialClientApplication.AcquireTokenForClient(scopesArr).ExecuteAsync();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
catch (Exception e)
{
}
}));
var bodyContent = MailBody;
string recep = toID;
var mail = new Mail(MailSubject, new string[] { recep }, new string[] { Cc });
var message = new Message
{
Subject = MailSubject,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = bodyContent
},
ToRecipients = mail.ToRecipients.Select(addr => new Recipient
{
EmailAddress = new EmailAddress { Address = addr }
}),
CcRecipients = mail.CcRecipients.Select(addr => new Recipient
{
EmailAddress = new EmailAddress { Address = addr }
})
};
await graphClient.Users["Graph User ID"]
.SendMail(message, false)
.Request()
.PostAsync();
}
We have used async methods in our application. So may be the Aync method is causing an issue for us.
Kindly help us to resolve or help to sending emails using Garph API without using Async method.
Thank you in advance.