1

I am working on task in ASP.NET Core 5 (C#) which requires to send an email using Graph API, I have referred to following article and did the configuration on the Azure trial account and was able to send the emails.

Sending e-mails with Microsoft Graph using .NET

This is the send email code:

//send email
var client = await GetAuthenticatedGraphClient();
    
await client.Users[senderObjectId]
                  .SendMail(graphMailMessage, true)
                  .Request()
                  .PostAsync();

senderObjectId - Object Id coming from config

We deployed the same code on the client's Azure account we needed the User Object Id for the service account that we are going to use as a sender's email id. However, the client came back saying that the account is not part of the Azure AD and its a service account. Is there a way of sending emails without using the user object id.

Ecstasy
  • 1,866
  • 1
  • 9
  • 17
Amitdh
  • 91
  • 1
  • 1
  • 6
  • 1
    You can this way `await _graphServiceClient.Me .SendMail(message, saveToSentItems) .Request()`, you can [`have a look on this official document`](https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=csharp#example-1-send-a-new-email-using-json-format) – Md Farid Uddin Kiron Apr 04 '22 at 11:23

1 Answers1

3

Here's the method which takes parameters for mail sending. Also, it separates (comma) the mail and sends it to multiple users

    public string SendEmail(string fromAddress, string toAddress, string CcAddress, string subject, string message, string tenanatID , string clientID , string clientSecret)
    {
            try
            {

                var credentials = new ClientSecretCredential(
                                    tenanatID, clientID, clientSecret,
                                new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud });
                GraphServiceClient graphServiceClient = new GraphServiceClient(credentials);


                string[] toMail = toAddress.Split(',');
                List<Recipient> toRecipients = new List<Recipient>();
                int i = 0;
                for (i = 0; i < toMail.Count(); i++)
                {
                    Recipient toRecipient = new Recipient();
                    EmailAddress toEmailAddress = new EmailAddress();

                    toEmailAddress.Address = toMail[i];
                    toRecipient.EmailAddress = toEmailAddress;
                    toRecipients.Add(toRecipient);
                }

                List<Recipient> ccRecipients = new List<Recipient>();
                if (!string.IsNullOrEmpty(CcAddress))
                {
                    string[] ccMail = CcAddress.Split(',');
                    int j = 0;
                    for (j = 0; j < ccMail.Count(); j++)
                    {
                        Recipient ccRecipient = new Recipient();
                        EmailAddress ccEmailAddress = new EmailAddress();

                        ccEmailAddress.Address = ccMail[j];
                        ccRecipient.EmailAddress = ccEmailAddress;
                        ccRecipients.Add(ccRecipient);
                    }
                }
                var mailMessage = new Message
                {
                    Subject = subject,

                    Body = new ItemBody
                    {
                        ContentType = BodyType.Html,
                        Content = message
                    },
                    ToRecipients = toRecipients,
                    CcRecipients = ccRecipients

                };
                // Send mail as the given user. 
                graphServiceClient
                   .Users[fromAddress]
                    .SendMail(mailMessage, true)
                    .Request()
                    .PostAsync().Wait();

                return "Email successfully sent.";

            }
            catch (Exception ex)
            {

                return "Send Email Failed.\r\n" + ex.Message;
            }
    }
Nahid
  • 336
  • 1
  • 12
  • I have registered an application in Azure DevOps. and am able to send email using only those office365 accounts which is available in the organization. But not able to send an email that is not part of that organization (any end-user accounts). Is there any way or any setting update missing from my side on Azure Portal? – Prashant Girase Feb 08 '23 at 13:38
  • 3
    Interesting. For me, this code `graphServiceClient.Users[fromAddress].SendMail(mailMessage, true)..` does not work! It does not expect using `SendMail(mailMessage, true)` as method. This is a property of `UserItemRequestBuilder` – T.S. Mar 14 '23 at 03:25
  • 1
    @T.S. There is a change on how to call SendMail. Please see this https://stackoverflow.com/questions/70771954/how-to-send-email-from-any-one-email-using-microsoft-graph – aravind Apr 10 '23 at 18:38