Search code examples
c#microsoft-graph-api

.net GraphServiceClient send email - code sample doesn't work anymore


I have found this example https://www.linkedin.com/pulse/sending-smtp-email-microsoft-graph-oauth-using-vbnet-elie-karkafy/ and rewrite it into c# like this:

static async Task SendEmail()
{
    var scopes = new[] { "https://graph.microsoft.com/.default" };

    var tenantId = ""; // Replace with your Tenant ID
    var clientId = ""; // Replace with Application ID from Overview tab
    var clientSecret = ""; // Replace with the Client Secret

    var options = new TokenCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    };

    var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
    var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

    var message = new Message
    {
        Subject = "This is the subject line",
        Body = new ItemBody
        {
            ContentType = BodyType.Text,
            Content = "This is the body of the email message."
        },
        ToRecipients = new List<Recipient>
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = "user@domain.com" // This is the recipient of the message
                }
            }
        }
    };

    await graphClient.Users["myuser@mydomain.com"].SendMail(message, null).Request().PostAsync();
}

But it seems that SDK has changed since it errors out with

Severity    Code    Description Project File    Line    Suppression State
Error   CS1955  Non-invocable member 'UserItemRequestBuilder.SendMail' cannot be used like a method.    MailSend    

at the line

await graphClient.Users["myuser@mydomain.com"].SendMail(message, null).Request().PostAsync();

I have found another example in C#: https://medium.com/medialesson/how-to-send-emails-in-net-with-the-microsoft-graph-a97b57430bbd

And it is basically the same code. So it seems that code was correct in previous versions.

I understand the basic of what the error is telling me, but I am not proficient enough in .net and Graph SDK to fix it. Any help and explanation is much appreciated.

EDIT

I have downgraded to graph 4 SDK and the followind code doesn't report any errors, but it doesn't work.

using Azure.Identity;
using Microsoft.Graph;

namespace MailSend1
{
    internal class Program
    {
        static void Main(string[] args)
        {

            await  SendEmail();
        }


        public static async Task SendEmail()
        {
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            var tenantId = ""; // Replace with your Tenant ID
            var clientId = ""; // Replace with Application ID from Overview tab
            var clientSecret = ""; // Replace with the Client Secret

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

            var message = new Message
            {
                Subject = "Just a test!",
                Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = "Does it work?"
                },
                ToRecipients = new List<Recipient>
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = "someuser@gmail.com" // This is the recipient of the message
                        }
                    }
                }
            };

            Console.WriteLine("Mail TO BE sent!");
            bool saveToSentItems = true;

            // Specify the user account to send from. An account in your tenant. It also sends the email.
            await graphClient.Users["test@somedomain.net"].SendMail(message, saveToSentItems).Request().PostAsync();

            Console.WriteLine("Mail sent!");
        }

    }
}

The issue is that code runs, but no mail is sent and no error reported. Also the second writeline statment is never printed.

What I am doing wrong?


Solution

  • The example is probably related to SDK v4, but you are using SDK v5 with breaking changes. The code for v5 should be like this

    static async Task SendEmail()
    {
        var scopes = new[] { "https://graph.microsoft.com/.default" };
    
        var tenantId = ""; // Replace with your Tenant ID
        var clientId = ""; // Replace with Application ID from Overview tab
        var clientSecret = ""; // Replace with the Client Secret
    
        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
        };
    
        var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
        var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
    
        var body = new SendMailPostRequestBody
        {
            Message = new Message
            {
                Subject = "This is the subject line",
                Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = "This is the body of the email message."
                },
                ToRecipients = new List<Recipient>
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = "user@domain.com" // This is the recipient of the message
                }
            }
        }
            }
        };
    
        await graphClient.Users["myuser@mydomain.com"].SendMail.PostAsync(body);
    }
    

    Upgrade to v5