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

时间:2019-03-29 17:08:32

标签: c# asp.net-mvc asp.net-core model-view-controller asp.net-identity

我已经制作了一个基本应用程序,用户可以在其中使用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>

EmailData

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);
        }
    }

}

AccountController

 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和其中的超长链接

2 个答案:

答案 0 :(得分:1)

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

message.IsBodyHtml = true;

答案 1 :(得分:0)

在我的EmailData脚本中从TextPart(“ plain”)更改为TextPart(“ html”)可以解决此问题。

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