从服务帐户使用 Graph API 发送电子邮件

发布于 2025-01-18 22:41:28 字数 702 浏览 0 评论 0原文

我正在 ASP.NET Core 5 (C#) 中执行任务,需要使用 Graph API 发送电子邮件,我参考了以下文章并在 Azure 试用帐户上进行了配置,并且能够发送电子邮件。

使用 .NET 通过 Microsoft Graph 发送电子邮件

这是发送电子邮件代码:

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

senderObjectId - 来自配置的对象 ID

我们在客户端的 Azure 帐户上部署了相同的代码,我们需要我们将用作的服务帐户的用户对象 ID发件人的电子邮件 ID。然而,客户回来说该帐户不是 Azure AD 的一部分,而是一个服务帐户。有没有一种方法可以在不使用用户对象 ID 的情况下发送电子邮件。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逆光下的微笑 2025-01-25 22:41:28

这是采用邮件发送参数的方法。另外,它将邮件分开(逗号)并将其发送给多个用户

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

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;
            }
    }
笑叹一世浮沉 2025-01-25 22:41:28

您只需在下面的 SendEmail 函数中将 clientId、tenantId、clientSecret 更改为您的 ID。确保安装了 Microsoft.GraphAzure.Identity nuget 包。

您需要在该函数之前添加以下代码:

using Microsoft.Graph;
using Microsoft.Graph.Models;
using Azure.Identity;
using Microsoft.Graph.Users.Item.SendMail;
using Message = Microsoft.Graph.Models.Message;
using FileAttachment = Microsoft.Graph.Models.FileAttachment;

如何使用:

_ = Task.Run(function: async () => await SendEmail("[email protected]", "[email protected];[email protected]", "[email protected]", "your subject", "your message in HTML format", "path/attachment1.xlsx;path/attachment2.pdf"));

您可以发送给多个人并附加多个文件,只需确保每个字符串之间用分号“;”分隔即可。它接受除 emFrom 和 emTo 变量之外的空字符串参数。

    public static async Task SendEmail(string emFrom, string emTo, string emCC, string emSubject, string emMessage, string emAttachment)
    {
        // Values from app registration
        string clientId = "";
        string tenantId = "";
        string clientSecret = "";

        var scopes = new[] { "https://graph.microsoft.com/.default" };
        var options = new ClientSecretCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud };
        var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
        var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

        var toRecipient = new List<Recipient>();
        foreach (string recipient in emTo.Split(";")) {
            toRecipient.Add(new Recipient { EmailAddress = new EmailAddress { Address = recipient } });
        }
        
        var ccRecipient = new List<Recipient>();
        if (!String.IsNullOrEmpty(emCC)) {
            foreach (string recipient in emCC.Split(";")) {
                ccRecipient.Add(new Recipient { EmailAddress = new EmailAddress { Address = recipient } });
            }
        }

        var attachments = new List<Attachment>();
        if (!String.IsNullOrEmpty(emAttachment))
        {
            var fileDict = new Dictionary<string, byte[]>(); // need to store the file byte into a dictionary before adding to email attachments
            foreach (string filePath in emAttachment.Split(";")) {
                fileDict.Add(Path.GetFileName(@filePath), File.ReadAllBytes(@filePath));
            }
            foreach (KeyValuePair<string, byte[]> entry in fileDict) {
                attachments.Add(new FileAttachment { OdataType = "#microsoft.graph.fileAttachment", Name = entry.Key, ContentBytes = entry.Value });
            }
        }

        var requestBody = new SendMailPostRequestBody
        {
            Message = new Message
            {
                Subject = emSubject,
                Body = new ItemBody { ContentType = BodyType.Html, Content = emMessage.Replace("\n", "<br>") },
                ToRecipients = toRecipient,
                CcRecipients = ccRecipient,
                Attachments = attachments
            },
            SaveToSentItems = true
        };

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

You just need to change clientId, tenantId, clientSecret to your IDs inside the SendEmail function below. Make sure to have Microsoft.Graph and Azure.Identity nuget packages installed.

You need the following code preceding the function:

using Microsoft.Graph;
using Microsoft.Graph.Models;
using Azure.Identity;
using Microsoft.Graph.Users.Item.SendMail;
using Message = Microsoft.Graph.Models.Message;
using FileAttachment = Microsoft.Graph.Models.FileAttachment;

How to use:

_ = Task.Run(function: async () => await SendEmail("[email protected]", "[email protected];[email protected]", "[email protected]", "your subject", "your message in HTML format", "path/attachment1.xlsx;path/attachment2.pdf"));

You can send to multiple people and attach multiple files, just make sure to separate each string with semi colon ";". It accepts empty string arguments except for the emFrom and emTo variables.

    public static async Task SendEmail(string emFrom, string emTo, string emCC, string emSubject, string emMessage, string emAttachment)
    {
        // Values from app registration
        string clientId = "";
        string tenantId = "";
        string clientSecret = "";

        var scopes = new[] { "https://graph.microsoft.com/.default" };
        var options = new ClientSecretCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud };
        var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
        var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

        var toRecipient = new List<Recipient>();
        foreach (string recipient in emTo.Split(";")) {
            toRecipient.Add(new Recipient { EmailAddress = new EmailAddress { Address = recipient } });
        }
        
        var ccRecipient = new List<Recipient>();
        if (!String.IsNullOrEmpty(emCC)) {
            foreach (string recipient in emCC.Split(";")) {
                ccRecipient.Add(new Recipient { EmailAddress = new EmailAddress { Address = recipient } });
            }
        }

        var attachments = new List<Attachment>();
        if (!String.IsNullOrEmpty(emAttachment))
        {
            var fileDict = new Dictionary<string, byte[]>(); // need to store the file byte into a dictionary before adding to email attachments
            foreach (string filePath in emAttachment.Split(";")) {
                fileDict.Add(Path.GetFileName(@filePath), File.ReadAllBytes(@filePath));
            }
            foreach (KeyValuePair<string, byte[]> entry in fileDict) {
                attachments.Add(new FileAttachment { OdataType = "#microsoft.graph.fileAttachment", Name = entry.Key, ContentBytes = entry.Value });
            }
        }

        var requestBody = new SendMailPostRequestBody
        {
            Message = new Message
            {
                Subject = emSubject,
                Body = new ItemBody { ContentType = BodyType.Html, Content = emMessage.Replace("\n", "<br>") },
                ToRecipients = toRecipient,
                CcRecipients = ccRecipient,
                Attachments = attachments
            },
            SaveToSentItems = true
        };

        await graphClient.Users[emFrom].SendMail.PostAsync(requestBody); 
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文