ASP.NEt Web API 2 SendEmailAsync不发送电子邮件?

时间:2015-11-16 05:02:59

标签: c# asp.net email asp.net-web-api2

我的ASP.Net Web-API2 Applicaiton的AccountController的注册方法有以下代码:

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
        // Send an email with this link
        string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

        // make sure token code is URLEncoded to make sure any special characters in code are allowed in URI to be created 
        //code = HttpUtility.UrlEncode(code);

        //create the URL to be put into the email
        var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }));

        //create Email
        string msgUserId = user.Id;
        string msgSubject = "Home Turf Network - Confirm your account";
        string msgBody = "Please confirm your Home Turf Network account by clicking <a href=\"" + callbackUrl + "\">here</a>";

        //send email
        await UserManager.SendEmailAsync(msgUserId, msgSubject, msgBody);

        return Ok();
        //return CreatedAtRoute("DefaultApi", new { id = user.Id }, user);
    }

它成功创建用户,创建代码,callbackURL,并从我可以告诉电子邮件发送到注册用户所需的一切。但电子邮件永远不会消失....

我测试了创建的callbackUrl,它在将数据库放入浏览器后成功注册了数据库中的电子邮件。如果电子邮件发出,它将完美地运作。

我尝试在我的IdentityConfig中设置一个断点,我的EmailService设置完毕,当我调试应用程序时它永远不会被触发,我无法弄清楚它为什么不发送电子邮件。

这是我的IdentityConfig.cs中的EmailService:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        //plug in your Email Service here to send an email
        MailMessage msg = new MailMessage(ConfigurationManager.AppSettings["mailAccount"], message.Destination, message.Subject, message.Body);
        msg.IsBodyHtml = true;

        using (SmtpClient client = new SmtpClient("smtp.gmail.com"))
        {
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential( ConfigurationManager.AppSettings["mailAccount"], ConfigurationManager.AppSettings["mailPassword"] );
            client.Port = 587;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            client.Send(msg);
        }

        return Task.FromResult(0);
    }
}

非常感谢任何追踪此问题的帮助。

0 个答案:

没有答案