Using MS Graph to send email from singe predefined/pre-set mailbox within .net web application

Julian Cram 25 Reputation points
2023-06-05T11:36:52.11+00:00

We need our application to send emails via MS Graph using a set single mailbox.

I have the following, but this is not working, with the following: 'Exception of type 'Microsoft.Graph.Models.ODataErrors.ODataError' was thrown'.

Digging into the details indicates an 'Access is denied' error.

Appropriate App registration in Azure was set-up with MS Graph Mail.Send permissions added.

I've tried the 'generic' email (no-reply@) and my own (the latter of which I know is included as a member of the app in Azure).

There appears to be a lack of documentation for using MS graph with .net, and/or a lack of documentation around sending emails using a pre-set mailbox (rather than asking the user for credentials).

Having pieced the below code together from a number of sources, I believe I need to retrieve and then pass with the sendmail.postAsync a token, but I'm stuck at this point.


 ClientSecretCredential credentials = new ClientSecretCredential(tenantId, clientId, mySecret, new TokenCredentialOptions() { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud });

    GraphServiceClient client = new GraphServiceClient(credentials);

    var eUser = client.Users("no-reply@domain.com");

    Await(eUser.SendMail.PostAsync(new Users.Item.SendMail.SendMailPostRequestBody() { Message = email, SaveToSentItems = true }));
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,430 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,415 questions
0 comments No comments
{count} votes

Accepted answer
  1. CarlZhao-MSFT 40,236 Reputation points
    2023-06-06T08:58:08.55+00:00

    Hi @Julian Cram

    You can use the graph C# SDK to send mail on behalf of users in the tenant. Before doing this, you need to grant the Mail.Send application permission to the calling app.

    Refer to the complete sample code:

    using Microsoft.Graph;
    using Azure.Identity;
    using Microsoft.Graph.Models;
    
    
    var scopes = new[] { "https://graph.microsoft.com/.default" };
    
    var tenantId = "{tenant id}";
    
    // Values from app registration
    var clientId = "{client id}";
    var clientSecret = "{client secret}";
    
    // using Azure.Identity;
    var options = new TokenCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    };
    
    // https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
    var clientSecretCredential = new ClientSecretCredential(
        tenantId, clientId, clientSecret, options);
    
    var accessToken = await clientSecretCredential.GetTokenAsync(new Azure.Core.TokenRequestContext(scopes) { });
    
    Console.WriteLine(accessToken.Token);
    
    var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
    
    var requestBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody
    {
        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 = "xxxx@xxxxxxxxxxx",
                    },
                },
            },
        },
        SaveToSentItems = false,
    };
    
    await graphClient.Users["{user id}"].SendMail.PostAsync(requestBody);
    

    By the way, with the graph SDK you don't need to manually add the access token as a request header, but you can export it in the console and decode it for troubleshooting.

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.


4 additional answers

Sort by: Most helpful
  1. TH-4749-MSFT 3,295 Reputation points
    2023-06-05T20:31:47.38+00:00

    Hello Julian Cram,

    Thanks for reaching out. You can find a C# SendMail Graph API example here. Replace the line:

    var requestBody = new Microsoft.Graph.Me.SendMail.SendMailPostRequestBody

    with :

    var requestBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody

    and line:

    await graphClient.Me.SendMail.PostAsync(requestBody);

    with

    await graphClient.Users[UserID].SendMail.PostAsync(requestBody);

    and change the emails To and From address and subject.

    Some of the properties are required such as To Address for example and cannot be omitted.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.

    Thanks.


  2. Julian Cram 25 Reputation points
    2023-06-06T08:26:11.2433333+00:00

    Removed as it should have been a comment on the first answer.

    0 comments No comments

  3. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  4. Akanchha Choubey 0 Reputation points
    2024-03-14T12:11:21.85+00:00

    Hi All,

    i have tried the same but I am getting an error always:

    HResult=0x80131500

    Message=One or more errors occurred. (OnBehalfOfCredential authentication failed: AADSTS50013: Assertion failed signature validation. [Reason - Key was found, but use of the key to verify the signature failed., Thumbprint of key used by client: 'XXXXXXXXXXXXX', Found key 'Start=02/08/2024 17:02:53, End=02/08/2029 17:02:53', Please visit the Azure Portal, Graph Explorer or directly use MS Graph to see configured keys for app Id '00000000-0000-0000-0000-000000000000'. Review the documentation at https://docs.microsoft.com/en-us/graph/deployments to determine the corresponding service endpoint and https://docs.microsoft.com/en-us/graph/api/application-get?view=graph-rest-1.0&tabs=http to build a query request URL, such as 'https://graph.microsoft.com/beta/applications/00000000-0000-0000-0000-000000000000']. Trace ID: YYYYYYYY Correlation ID: zzzzzzzzzzzzz Timestamp: 2024-03-14 12:01:44Z)

    Source=System.Private.CoreLib

    StackTrace:.........

    Can some one please help what is the issue here.

    0 comments No comments