使用AzureAD经过身份验证的用户发送Office365电子邮件

时间:2018-02-05 05:55:19

标签: asp.net-core-mvc office365 azure-active-directory azure-ad-graph-api

我有一个.Net Core MVC Web应用程序,它使用AzureAD对用户进行身份验证。在某些阶段,我需要代表该用户发送电子邮件。 我搜索了一些选项,显然我可以使用Microsoft Exchange Service或Office365执行此操作,但对于这两个选项,我需要获取用户的凭据。

使用Office365的示例如下,但我不知道如何使用签名信息传递给SMTP服务器。

我的(部分)HomeController:

private readonly ClaimsPrincipal _principal;
public HomeController(IPrincipal principal){                
            _principal = principal as ClaimsPrincipal;                
        }

我可以使用_principal.FindFirst(ClaimTypes.Upn).Value获取用户的电子邮件地址,但如何获取密码?

我是在正确的道路上还是我错过了什么?

public static void SendEmail(string toAddress, string fromAddress, string subject, string content)
    {
        SmtpClient client = new SmtpClient();
        client.Credentials = new NetworkCredential("", "");
        client.Port = 587;
        client.Host = "smtp.office365.com"; 
        client.EnableSsl = true;            

        MailMessage newMail = new MailMessage();
        newMail.To.Add(toAddress);

        newMail.From = new MailAddress(fromAddress);
        newMail.Subject = subject;
        newMail.IsBodyHtml = true;
        newMail.Body = "<html><body>" + content + "</body></html>";                        

        client.Send(newMail);
    }

对不起,如果这是一个广泛的问题,但我真的需要了解如何实现这一目标。如有必要,我很乐意提供更多详细信息。

1 个答案:

答案 0 :(得分:0)

  

在某个阶段,我需要代表该用户发送电子邮件。

根据我的理解,您可以使用connect middleware SendGrid代表您经过身份验证的用户的电子邮件地址处理电子邮件递送。向用户test02@example.com发送电子邮件至test01@example.com的代码如下所示:

var client = new SendGridClient("<SendGrid-ApiKey>");
var msg = new SendGridMessage()
{
    From = new EmailAddress("test01@example.com", "test01"),
    Subject = "Hello World from the SendGrid CSharp SDK!",
    PlainTextContent = "Hello, Email!",
    HtmlContent = "<strong>Hello, Email!</strong>"
};
msg.AddTo(new EmailAddress("test02@example.com", "Test02"));
var response = await client.SendEmailAsync(msg);

详细教程,您可以关注cloud-based email service

相关问题