Home > Software design >  How to send email from any one email using Microsoft Graph
How to send email from any one email using Microsoft Graph

Time:01-20

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);

CodePudding user response:

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 = "[email protected]"
            }
        }
    }
};

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:

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 = "[email protected]"
            }
        }
    },
    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();
  •  Tags:  
  • Related