[英]Asp.Net Identity 2.0 - How to Implement IIdentityMessageService to do Async SMTP using SmtpClient?
[英]How to use SMTP or Office 365 account in ASP.Net IIdentityMessageService?
我曾經使用 web.config 配置我的 SMTP 帳戶,以便能夠使用發送電子郵件功能,但 ASP.Net Identity 要求提供電子郵件服務。 如何在以下區域使用 SMTP 或 Office 365 電子郵件:
IdentityResult result = manager.Create(user, Password.Text );
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
string code = manager.GenerateEmailConfirmationToken(user.Id);
string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");
signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
ErrorMessage.Text = result.Errors.FirstOrDefault();
}
public Task SendAsync(IdentityMessage message)
{
// Credentials:
var credentialUserName = "test@test.com";
var sentFrom = "test@test.com";
var pwd = "testpassword";
// Configure the client:
System.Net.Mail.SmtpClient client =
new System.Net.Mail.SmtpClient("smtp-mail.outlook.com");
client.Port = 587;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
// Create the credentials:
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(credentialUserName, pwd);
client.EnableSsl = true;
client.Credentials = credentials;
// Create the message:
var mail =
new System.Net.Mail.MailMessage(sentFrom, message.Destination);
mail.Subject = message.Subject;
mail.Body = message.Body;
// Send:
return client.SendMailAsync(mail);
// Plug in your email service here to send an email.
//return Task.FromResult(0);
}
<system.net>
<mailSettings>
<smtp>
<network defaultCredentials="true" enableSsl="true" host="smtp.office365.com" port="587" password="password" userName="username" />
</smtp>
</mailSettings>
</system.net>
感謝您為解決我的問題所做的努力。
在EmailService.SendTaskAsync
有一條注釋告訴您在何處插入電子郵件代碼。 這是您放置 SMTP 代碼、調用 Office 365 API 或 Web 服務(如SendGrid )的地方。 這是使用 SMTP 的示例。
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
//create a client, it should pick up the settings from web.config
var client = new SmtpClient();
//now construct a MailMessage object from the message
var email = new MailMessage("donotreply@mysite.com", message.Destination, message.Subject, message.Body);
//send the email asynchronously
await client.SendMailAsync(email);
return Task.FromResult(0);
}
}
顯然,您可能希望將實際的電子郵件代碼移動到另一個類,以便您可以將其重用於其他與電子郵件相關的任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.