如何修复电子邮件确认-在.NET Core中,它不起作用 [英] How can I fix email confirmation - in .NET Core, it doesn't work

查看:75
本文介绍了如何修复电子邮件确认-在.NET Core中,它不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有注册操作

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注册了它们,然后创建了发送电子邮件的操作

Then I created the sendgrid user and key and registered them by CMD, then I created the action of send email

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中

Then in 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");
            });
}

但是注册后发送电子邮件不起作用,这给了我一些我需要确认我的电子邮件的单词,并给了我确认我的电子邮件的链接,但没有将其发送给gmail

but sending an e-mail doesn't work after registration gives me some words that i need confirm my email and gives me link to confirm my email but doesn't send it to gmail

有人有想法吗?

我遵循了Microsoft的本文档 https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/accconfirm?view = aspnetcore-3.1& tabs = visual-studio

I followed this documentation from microsoft https://docs.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio

推荐答案

已解决",我问Sendgrid,并被告知不能将yahoo电子邮件(或gmail,...)用作发件人电子邮件;这是答案的一部分:"Yahoo遵守称为DMARC的电子邮件安全标准.DMARC指示电子邮件提供商拒绝发件人"域为Yahoo域但邮件来自未经批准的域服务器/服务的邮件."所以我需要使用自己的邮件域;

"Solved" I asked Sendgrid, and I was told that I cannot use my yahoo email (or gmail,...) as the sender email; this is part of the answer: "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." So I need to use my own mail domain;

这篇关于如何修复电子邮件确认-在.NET Core中,它不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆