我正在 ASP.NET Core 5 (C#) 中执行任务,需要使用 Graph API 发送电子邮件,我参考了以下文章并在 Azure 试用帐户上进行了配置,并且能够发送电子邮件。
使用 .NET 通过 Microsoft Graph 发送电子邮件 https://zimmergren.net/sending-e-mails-using-microsoft-graph-using-dotnet/
这是发送电子邮件的代码:
//send email
var client = await GetAuthenticatedGraphClient();
await client.Users[senderObjectId]
.SendMail(graphMailMessage, true)
.Request()
.PostAsync();
senderObjectId
- 来自配置的对象 ID
我们在客户端的 Azure 帐户上部署了相同的代码,我们需要服务帐户的用户对象 ID,并将其用作发件人的电子邮件 ID。然而,客户回来说该帐户不是 Azure AD 的一部分,而是一个服务帐户。有没有一种方法可以在不使用用户对象 ID 的情况下发送电子邮件。
这是采用邮件发送参数的方法。此外,它还分隔了 (comma) 邮件并将其发送给多个用户
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)