如何将电子邮件确认代码作为 html 链接发送



我制作了一个基本的应用程序,用户可以在其中使用 asp.net 核心身份框架进行注册。

当用户注册时,他们会收到一个确认代码,他们单击该代码以确认其帐户并登录。

问题是我不想要电子邮件中随机生成的大长链接,我正在尝试将链接传递到带有一些 html 的"标签中。不幸的是,电子邮件完全忽略了 html 格式,并将所有内容作为一个大的长字符串发送。

我觉得我已经尝试了每种不同的组合,所以愿意接受任何建议

这是我收到的一封电子邮件的示例

Please confirm your account by clicking this link: <a 
href='https://localhost:44380/Account/ConfirmEmail?userId=02678522-9cca- 
41a3-b6ad5ffbc66335d0&token=CfDJ8JiT8fifBtNEgqHa2cUXO7tOkDv6hjChQMu4I7j99p0B 
nc2UEc8wV6QnL2lQPau%2BmdoGBPK3ic4ocy2M6K4bIrJnzvFmGFVxqOnKx3nZn3896SuUO1dpR 
L7DHahnHP3Wy5JZlyFJrkJ5ncnF%2BUXpJoBzS%2FupjkJ4kv5SUxwQ0V3 
ytb7jKdv0pEs7mtEfcDlO%2B8EcdJdEJMQePfwf%2FPr73IrOrSU499WLon0kFfzN0qg 
jQOe0lI7yuDZv1aam udb1g%3D%3D'>Confirm</a>

电子邮件数据

public class EmailData
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly EFCoreOrganisationDb _context;
    public EmailData(UserManager<ApplicationUser> userManager, 
SignInManager<ApplicationUser> signInManager, EFCoreOrganisationDb 
context)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _context = context;
    }

    public static void SendAuth(string userName, string userEmail, string 
cTokenLink)
    {
        //this didnt work
        //string body = @"<html><body><a href='+cTokenLink+'>here</a> 
 </body></html>";
        var bodyBuilder = new BodyBuilder();
        bodyBuilder.HtmlBody = String.Format("Click here {0} to confirm 
your email address", cTokenLink);

        string body = bodyBuilder.HtmlBody;

        string SenderName = "BlabberApp";
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress(SenderName, "************"));
        message.To.Add(new MailboxAddress(userName, userEmail));
        message.Subject = "Email Confirmation From Blabber";
        message.Body = new TextPart("plain")
        {
            Text = body
        };
        using (var client = new SmtpClient())
        {
            client.Connect("smtp.gmail.com", 587, false);
            client.Authenticate("************", "**********");
            client.Send(message);
            client.Disconnect(true);
        }
    }
}

帐户控制器

 public class AccountController : Controller
 {
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly EFCoreOrganisationDb _context;
    public AccountController(UserManager<ApplicationUser> userManager, 
 SignInManager<ApplicationUser> signInManager, EFCoreOrganisationDb 
 context)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _context = context;
    }
    [HttpGet]
    public IActionResult Login()
    {
        return View();
    }
    [HttpPost]
    public async Task<IActionResult> Login(LoginViewModel vm)
    {
        if (ModelState.IsValid)
        {
            var result = await 
 _signInManager.PasswordSignInAsync(vm.Email, vm.Password, vm.RememberMe, 
 false);
            if (result.Succeeded)
            {
                return View("../Home/Index");
            }
            var error = result.ToString();
           if (error.Count() > 1)
            {
                ModelState.AddModelError("", "Invalid Login Attempt" );
            }
            return View(vm);
        }
        return View(vm);
    }
    [HttpPost]
    public async Task<IActionResult> Logout()
    {
        await _signInManager.SignOutAsync();
        return RedirectToAction("Index", "Home");
    }
    [HttpGet]
    public IActionResult Register()
    {
        return View();
    }
    [HttpPost]
    public async Task<IActionResult> Register(RegisterViewModel vm)
    {
        try
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = vm.Email, 
 Email = vm.Email };
                var result = await _userManager.CreateAsync(user, 
 vm.Password);
                await _userManager.AddToRoleAsync(user, "User");
                if (result.Succeeded)
                {
                    string cToken = await 
 _userManager.GenerateEmailConfirmationTokenAsync(user);
                    string cTokenLink = Url.Action("ConfirmEmail", 
 "Account", new
                    {
                        userId = user.Id,
                    token = cToken
                    },protocol:HttpContext.Request.Scheme);

 EmailData.SendAuth(user.UserName,user.Email,cTokenLink);
                    //ViewBag.token = cTokenLink;

                    await _signInManager.SignInAsync(user, false);
                    return View(vm);
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
        }
        catch(Exception ex)
        {
        }
        return View(vm);
    }
    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> ConfirmEmail(string userId, string 
 token)
    {
        if(userId == null || token == null)
        {
            return View("Error"); 
        }
        var user = await _userManager.FindByIdAsync(userId);
        if(user == null)
        {
            return View("Error");
        }
        var result = await _userManager.ConfirmEmailAsync(user, token);
        return View(result.Succeeded ? "ConfirmEmail" : "Error");
    }
 }

我希望这会发送带有一句话和一个可点击链接的电子邮件。

相反,它发送原始html和其中的超长链接

通过添加以下行在邮件正文中启用 html:

message.IsBodyHtml = true;

在我的

EmailData脚本中从TextPart("plain"(更改为TextPart("html"(解决了这个问题。

感谢@Chris Pratt向我指出这一点

相关内容

  • 没有找到相关文章

最新更新