gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:24:22 26 4
gpt4 key购买 nike

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

Sending e-mails with Microsoft Graph using .NET

这是发送电子邮件的代码:

//send email
var client = await GetAuthenticatedGraphClient();

await client.Users[senderObjectId]
.SendMail(graphMailMessage, true)
.Request()
.PostAsync();

senderObjectId - 来自配置的对象 ID

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

最佳答案

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

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

关于c# - 从服务帐户使用 Graph API 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71736036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com