3

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:

enter image description here

I made sure to provide the client id, tenant id, client secret.

However, I see this error on running the console:

enter image description here

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 = "myToEmail@gmail.com"
                    }
                }
            },
            CcRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = "myCCEmail@gmail.com"
                    }
                }
            }
        };

        var saveToSentItems = true;

          await graphClient.Me
            .SendMail(message, saveToSentItems)
            .Request()
            .PostAsync();

        return graphClient;

    }
user989988
  • 3,006
  • 7
  • 44
  • 91

1 Answers1

4

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.

Allen Wu
  • 15,529
  • 1
  • 9
  • 20
  • Thank you! On using graph.microsoft.com/v1.0/me/sendMail, what will be the Sender Address? – user989988 Oct 09 '20 at 23:40
  • Also, is there a way to provide a random sender address (eg: abc-noreply@microsoft.com) and send email using the above graph api calls? – user989988 Oct 10 '20 at 00:11
  • @user989988 Sorry for the delay. I was OOF the other day. If you want to use `/me/sendMail`, you will be required to use [Authorization code provider](https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#AuthCodeProvider). That means you will need to sign in with your account. So the Sender Address is the sign-in user in this case. – Allen Wu Oct 16 '20 at 06:23
  • @user989988 Can you explain more about random sender address? Do you mean you don't want to use a real email address? I don't think this is reasonable. O365 requires an exchange online license to send emails. You need to make sure the sender is real. – Allen Wu Oct 16 '20 at 06:27
  • Thank you! So, if I create a test user with an email address and use that as sender address, would that work? On setting userPrincipalName of a user that already exists in my tenant as sender, it works perfectly. After creating a user in my tenant and using that userPrincipalName as sender, I don't see any emails being sent. Why is that? Am I missing something? – user989988 Oct 17 '20 at 01:33
  • @user989988 Did you assign exchange online license to the test user? If not, the test user cannot send email. See https://learn.microsoft.com/en-us/microsoft-365/admin/manage/assign-licenses-to-users?view=o365-worldwide – Allen Wu Oct 19 '20 at 01:49
  • Thank you! I see 4 options for the licenses to assign - Enterprise Mobility + Security E5, Office 365 E5, Office 365 F3, Windows 10 Enterprise E3. Which license should I assign to the test user? Please let me know. – user989988 Oct 19 '20 at 04:13
  • Thank you so much! Do you know the procedure for getting licenses to a new user in Microsoft Tenant? – user989988 Oct 19 '20 at 04:56
  • @user989988 I think you can assign O365 E5 to the test user. The procedure is in the link I shared. Do you have any issues on doing this? – Allen Wu Oct 19 '20 at 05:12
  • From my demo tenant I’m able to add license to the test user because I’m an admin. But in Microsoft tenant, I’m not an admin. So, I wonder if the procedure is different. – user989988 Oct 19 '20 at 05:38
  • @user989988 Oh you can't assign license in Microsoft Tenant if you are not admin. – Allen Wu Oct 19 '20 at 05:42
  • Got it. Thank you! – user989988 Oct 19 '20 at 06:04
  • @user989988 If you have any other questions please let me know. And if my answer is helpful, you can mark it as accepted. Thank you. – Allen Wu Oct 19 '20 at 06:19
  • On using userPrincipalName of sender I see it working. On replacing it with Id, it is not working. Could you please let me know why is that? – user989988 Oct 19 '20 at 19:30
  • Also, if I want to use https://graph.microsoft.com/v1.0/me/sendMail, what should I set as scopes variable & redirectUri? I updated the code: var authProvider = new AuthorizationCodeProvider(confidentialClientApplication); however https://graph.microsoft.com/v1.0/me/sendMail is not working for me. What am I missing? Please let me know. – user989988 Oct 19 '20 at 21:20
  • @user989988 Id should also work. Please make sure you are using the correct id. What is the error while using Id? Besides, if you want to use `/me/sendMail`, you need to implement Interactive login. Please refer to this sample: https://learn.microsoft.com/en-us/learn/modules/msgraph-build-aspnetmvc-apps/5-exercise-add-auth. – Allen Wu Oct 20 '20 at 02:45
  • @user989988 I notice that the new post is deleted. Have you resolved it? – Allen Wu Oct 22 '20 at 01:54
  • Hi, I got it working for one of the users in my tenant after adding licenses. However, I have a user MOD Administrator which has all the licenses required. When I set MOD Admin as the test user, I don't see any emails being sent. Could you please let me know what could be the reason? – user989988 Oct 22 '20 at 01:55
  • @user989988 If you just assign the license, maybe you should wait a moment. This kind of problem lacks troubleshooting conditions, it is difficult for me to locate the root cause for you. BTW, the original problem of this post has been solved, can you mark my answer? – Allen Wu Oct 22 '20 at 02:06
  • Thank you! Marked your answer. Also, what could be thre reason for showing the error: Message: REST API is not yet supported for this mailbox. – user989988 Oct 22 '20 at 02:15
  • 1
    @user989988 This means the user doesn't has Exchange Online license. – Allen Wu Oct 22 '20 at 02:16
  • Cool, thank you! I see that all emails being sent to junk folder instead of inbox folder. Could you please let me know why is that. – user989988 Oct 22 '20 at 04:13
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223437/discussion-between-allen-wu-and-user989988). – Allen Wu Oct 22 '20 at 05:39
  • Could you please please give an example of implementing interactive login for using /me/sendMail? – user989988 Jan 26 '21 at 11:37
  • Is it possible to send emails by any end users, which have office365, outlook accounts? I have registered an application in Azure DevOps. and I am able to send email using only those office365 accounts which is available in the organization/domain. But not able to send an email that is not part of that organization/domain(any end-user accounts). – Prashant Girase Feb 15 '23 at 13:36