如何修复电子邮件确认 - 在 .NET Core 中,它不起作用
How can I fix email confirmation - in .NET Core, it doesn't work
我已经有一个注册操作
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
var useremail = _userManager.Users.FirstOrDefault(u => u.Email.ToLower() == Input.Email.ToLower());
if (useremail == null)
{
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
// If we got this far, something failed, redisplay form
ViewData["EmailExists"] = "Try another email that one is used";
return Page();
}
然后我创建了 sendgrid 用户和密钥并通过 CMD 注册它们,然后我创建了发送电子邮件的动作
public class EmailSender : IEmailSender
{
public EmailSender(IOptions<AuthMessageSenderOptions>optionsAccessor)
{
Options = optionsAccessor.Value;
}
public AuthMessageSenderOptions Options { get; }
public Task SendEmailAsync (string email , string subject , string message)
{
return Excute(Options.SendGridKey,subject,message,email);
}
private Task Excute(string apiKey, string subject, string message, string email)
{
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("darydress@yahoo.com", "dary dress"),
Subject = subject,
PlainTextContent = message,
HtmlContent = message
};
msg.AddTo(new EmailAddress(email));
msg.SetClickTracking(false, false);
return client.SendEmailAsync(msg);
}
}
然后在 startup.cs
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>( options => options.SignIn.RequireConfirmedAccount = true)
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddMvc();
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddPaging();
services.ConfigureApplicationCookie(o => {
o.ExpireTimeSpan = TimeSpan.FromDays(5);
o.SlidingExpiration = true;
});
services.AddMvc(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Main/AccessDenied");
});
}
但是注册后发送电子邮件不起作用给我一些我需要确认我的电子邮件的词并给我 link 确认我的电子邮件但不发送到 gmail
有人有想法吗?
当我使用个人用户帐户创建一个新的 Web 应用程序时,这非常有效,但我注意到,当您构建标识并覆盖所有页面以控制现有应用程序时,您遇到的行为是正常的。
这是我修复它的方法:
如果您打开文件 Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs
查找注释 Once you add a real email sender, you should remove this code that lets you confirm the account
,注释 return Page() 语句之前该行下方的所有内容,这应该可以完成工作。
"Solved" 我问过 Sendgrid,我被告知我不能使用我的 yahoo 电子邮件(或 gmail,...)作为发件人电子邮件;这是部分答案:"Yahoo observes an email security standard called DMARC. DMARC instructs email providers to reject messages where the From domain is a Yahoo domain, but the message originates from a non-approved domain server/service." 所以我需要使用自己的邮件域;
我已经有一个注册操作
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
var useremail = _userManager.Users.FirstOrDefault(u => u.Email.ToLower() == Input.Email.ToLower());
if (useremail == null)
{
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
// If we got this far, something failed, redisplay form
ViewData["EmailExists"] = "Try another email that one is used";
return Page();
}
然后我创建了 sendgrid 用户和密钥并通过 CMD 注册它们,然后我创建了发送电子邮件的动作
public class EmailSender : IEmailSender
{
public EmailSender(IOptions<AuthMessageSenderOptions>optionsAccessor)
{
Options = optionsAccessor.Value;
}
public AuthMessageSenderOptions Options { get; }
public Task SendEmailAsync (string email , string subject , string message)
{
return Excute(Options.SendGridKey,subject,message,email);
}
private Task Excute(string apiKey, string subject, string message, string email)
{
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("darydress@yahoo.com", "dary dress"),
Subject = subject,
PlainTextContent = message,
HtmlContent = message
};
msg.AddTo(new EmailAddress(email));
msg.SetClickTracking(false, false);
return client.SendEmailAsync(msg);
}
}
然后在 startup.cs
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>( options => options.SignIn.RequireConfirmedAccount = true)
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddMvc();
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddPaging();
services.ConfigureApplicationCookie(o => {
o.ExpireTimeSpan = TimeSpan.FromDays(5);
o.SlidingExpiration = true;
});
services.AddMvc(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Main/AccessDenied");
});
}
但是注册后发送电子邮件不起作用给我一些我需要确认我的电子邮件的词并给我 link 确认我的电子邮件但不发送到 gmail
有人有想法吗?
当我使用个人用户帐户创建一个新的 Web 应用程序时,这非常有效,但我注意到,当您构建标识并覆盖所有页面以控制现有应用程序时,您遇到的行为是正常的。
这是我修复它的方法:
如果您打开文件 Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs
查找注释 Once you add a real email sender, you should remove this code that lets you confirm the account
,注释 return Page() 语句之前该行下方的所有内容,这应该可以完成工作。
"Solved" 我问过 Sendgrid,我被告知我不能使用我的 yahoo 电子邮件(或 gmail,...)作为发件人电子邮件;这是部分答案:"Yahoo observes an email security standard called DMARC. DMARC instructs email providers to reject messages where the From domain is a Yahoo domain, but the message originates from a non-approved domain server/service." 所以我需要使用自己的邮件域;