使用SendGrid v3将身份模板作为确认电子邮件发送身份

时间:2017-12-04 15:20:13

标签: c# asp.net-mvc asp.net-identity sendgrid sendgrid-api-v3

我是asp.net mvc Identity和SendGrid的新手,但我真的很想使用它们的功能。

我想让用户使用身份注册表单注册,然后使用SendGrid v3发送模板(内置在我的SendGrid帐户中)作为帐户注册确认电子邮件。我创建了一个Transactional模板,并有一个Api Key。

我已在身份中启用了电子邮件确认:

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");

然后我在web.config的应用程序设置中设置了sendGrid apiKey和帐户凭据,以便我可以在我的代码中使用它们。

<appSettings>
  <add key="SendGridUsername" value="xxxxxxx" />
  <add key="SendGridPassword" value="xxxxxxx" />
  <add key="SendGridApiKey" value="xxxxxxxxxxxxxxxxxxxxxxxx" />
</appSettings>

我已经在IdentityConfig.cs中将其添加到我的EmailService中,但我仍然坚持从这里开始:

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email. 
        var apiKey = WebConfigurationManager.AppSettings["SendGridApiKey"];
        var client = new SendGridClient(apiKey);
        var from = new EmailAddress("me@us.com", "Me");
        var subject = message.Subject;
        var to = new EmailAddress(message.Destination);
        var email = MailHelper.CreateSingleEmail(from, to, subject, "", message.Body);
        await client.SendEmailAsync(email);
    }
}

我也阅读了以下内容,但无法理解在哪里实施它:

https://sendgrid.com/docs/API_Reference/Web_API_v3/Transactional_Templates/smtpapi.html

{
  "filters": {
    "templates": {
      "settings": {
        "enable": 1,
         "template_id": "5997fcf6-2b9f-484d-acd5-7e9a99f0dc1f"
       }
     }
   }
}

任何有关这方面的帮助都会很棒,因为我不知道从哪里开始。

由于

2 个答案:

答案 0 :(得分:3)

您可以使用以下代码在电子邮件中发送交易模板:

        var apiKey = AppConstants.JuketserSendGridKey;
        var client = new SendGridClient(apiKey);

        var msg = new SendGridMessage();
        msg.SetFrom(new EmailAddress("admin@jukester.com", "Jukester"));
        //msg.SetSubject("I'm replacing the subject tag");
        msg.AddTo(new EmailAddress(model.EmailTo));
        //msg.AddContent(MimeType.Text, "I'm replacing the <strong>body tag</strong>");
        msg.SetTemplateId("Your TemplateId here");

        var response = await client.SendEmailAsync(msg);
        var status = response.StatusCode.ToString();
  

编辑您的其他问题:

对于电子邮件确认方案,您必须在用户注册时向已注册的电子邮件发送电子邮件。创建验证令牌并将其保存在数据库中。该电子邮件将包含一些链接或按钮。此链接或按钮将包含该验证令牌。用户单击该链接/按钮后,将在项目中调用webapi或操作方法,您将验证验证码,然后更新数据库中EmailConfirmed的状态。

以下是我所做的一些代码片段,它们可能会对您有所帮助。

以下代码创建验证码并更新数据库中的用户记录。

var encryptedToken = Utility.Crypt(user.Email);
var updateStatus = await UpdateVerificationCode(userToAdd, encryptedToken);

然后,以下验证码传递给需要在电子邮件中发送的数据。 “paramList”是一个数据列表。

if (updateStatus)
{
    paramList.Add(encryptedToken);
    var emailModel = Utility.CreateEmailModel(user.Email, paramList, AppConstants.RegistrationTemplateId, (int)EmailType.Register);
    await Helper.SendEmail(emailModel);

}

现在,此代码将附在发送给用户的电子邮件中的链接或按钮中,以进行电子邮件验证。当用户单击该链接/按钮时,将调用web api操作方法进行电子邮件验证。

public async Task<GenericResponse> ConfirmEmail(SetPasswordBindingModel model)
    {
        var response = new GenericResponse();
        if (model != null)
        {
            try
            {
                var user = await _aspNetUserService.GetByEmail(model.Email);
                if (user != null)
                {
                    if (!string.IsNullOrEmpty(model.VerificationCode))
                    {
                        //if time difference is less than 5 minutes then proceed
                        var originalKey = Utility.Decrypt(model.VerificationCode);
                        if (user.Email == originalKey)
                        {
                            var emailConfirmationCode = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                            var result = await UserManager.ConfirmEmailAsync(user.Id, emailConfirmationCode);
                            if (result.Succeeded)
                            {
                                var status = await _aspNetUserService.ResetVerificationCode(model.Email);
                                if (status)
                                {
                                    response.Message = AppConstants.EmailConfirmed;
                                    response.IsSuccess = true;
                                }
                            }
                            else
                            {
                                response.Message = AppConstants.Error;
                                response.IsSuccess = false;
                            }
                        }
                        else
                        {
                            response.Message = AppConstants.InvalidVerificationCode;
                            response.IsSuccess = false;
                        }
                    }
                    else
                    {
                        response.Message = AppConstants.InvalidVerificationCode;
                        response.IsSuccess = false;
                    }
                }
                else
                {
                    response.Message = AppConstants.NoUserFound;
                    response.IsSuccess = false;
                }
            }
            catch (Exception ex)
            {
                //response.Message = AppConstants.Error;
                response.Message = ex.Message;
            }

        }
        return response;
    }

您可以查看它,如果它可以帮助您的需要,请使用它。感谢

答案 1 :(得分:-1)

@DBoi: var result = await UserManager.ConfirmEmailAsync(user.Id, emailConfirmationCode);将负责相应的确认和更新位。