我正在 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 的情况下发送电子邮件。
这里是接收邮件发送参数的方法。此外,它分隔(逗号)邮件并将其发送给多个用户
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;
}
}
您需要 clientId、tenantId、clientSecret 才能正常工作。
使用方法:
_ = Task.Run(function: async () => await Send_Email("", "", "", "", "", ""));
您可以发送给多人并附加多个文件,只需确保用分号“;”分隔每个字符串即可。
public static async Task SMTP2(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);
}