5

I am using microsoft graph to send email. This email I want to send from any email that exists in the Active directory. I already have get the permission on Mail.Send and have admin consent on Azure.So all set on the Azure level for access and permission.

Now when come to code. I have searched for but I am not able to figure out how to call the Microsoft graph api to send the email. Below is the code that I have been finding when I am doing search. How I can replace the below code to send the email to anyone from anyone in Azure AD to anyone in Azure AD. Also the code for send email 'Send AS'.

  await graphClient.Me.Messages
              .Request()
                .AddAsync(message);
Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
Jashvita
  • 553
  • 3
  • 24

3 Answers3

8

Please note that since Graph API v. 5.0 (march 2023), Microsoft introduced an annoying breaking change, not really well documented (besides obscurely here).

Now, SendMail cannot be used anymore as a method of a User. You will get a CS1955 Non-invocable member cannot be used like a method compiler error if you try to do that.

You will have to do something like this:

        // Your old Message object definition
        Microsoft.Graph.Models.Message msg = new()
        {
            From = ...,
            ToRecipients = ...,
            Subject = "...",

            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = "..."
            }
        };

        Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody body = new()
        {
            Message = msg,
            SaveToSentItems = false  // or true, as you want
        };

        try
        {
            await graphClient.Users["your user GUID"]
            .SendMail
            .PostAsync(body);
        }
        catch (Exception ex)
        {
            // log your exception here
        }
davidthegrey
  • 1,205
  • 2
  • 14
  • 23
3

The intention is the signed in user will not send email from his email address, the email notification will be asthmatically sent by someone else name to someone.

Then I think you wanna provide a sending email to your users, users can choose who received the email, but all the email should be sent be a specific account, such as admin@xxx.onmicrosoft.com, then you should know something about the sending email api.

As @user2250152 mentioned, await graphClient.Users["userId"], here the userId means who send the email, as your requirement is sending all emails from one specific email address, it should hardcode as admin@xxx.onmicrosoft.com.

The next is how to send the email, calling ms graph api should offer an access token, as your requirement is sending email by the application but not every user, so I'm afraid the client credential flow is a better choice so that when the scenario comes to sending email from several specific email addresses, you don't need to change the flow then. Now you need to require your tenant admin to add Mail.Send Application api permission in azure ad to use this kind of flow.

enter image description here

And here's the code:

using Azure.Identity;
using Microsoft.Graph;
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
            {
                //who will receive the email
                Address = "xxx@gmail.com"
            }
        }
    },
    Attachments = new MessageAttachmentsCollectionPage()
};

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_client_id";
var clientSecret = "client_secret_for_the_azuread_app";
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
await graphClient.Users["user_id_which_you_wanna_used_for_sending_email"].SendMail(mesg, false).Request().PostAsync();
Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
1

You can send mail from other user this way.

var message = new Message
{
    Subject = "Subject",
    Body = new ItemBody
    {
        ContentType = BodyType.Text,
        Content = "Content"
    },
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "john.doe@contoso.onmicrosoft.com"
            }
        }
    }
};

var saveToSentItems = false;

await graphClient.Users["userId"]
    .SendMail(message,saveToSentItems)
    .Request()
    .PostAsync();

userId is the unique identifier for the user. Instead of userId you can use userPrincipalName. The UPN is an Internet-style login name for the user based on the Internet standard RFC 822. By convention, this should map to the user's email name.

Resources:

Send mail

User resource

user2250152
  • 14,658
  • 4
  • 33
  • 57
  • What is that userId would be? await graphClient.Users["userId"] – Jashvita Jan 19 '22 at 14:25
  • @Salma userId is a unique identifier of the user. As an alternative you can use user mail instead of user id. I've updated the answer. – user2250152 Jan 19 '22 at 14:37
  • Hi , actually I am looking for if signed in user is sending email on the name of someone else. Then whose userId would go there. The intention is the signed in user will not send email from his email address, the email notification will be asthmatically sent by someone else name to someone. Or I need to get the userid and hardcode it which maybe not right. – Jashvita Jan 19 '22 at 17:02