如何在IdentityConfig.cs中配置电子邮件服务类以在ASP.NET中发送密码重置电子邮件



我正在在ASP.NET MVC中开发一个应用程序,其中一个要求是重置密码功能,我无法弄清楚如何发送密码恢复电子邮件,以便用户可以重置密码。

这是我在Web配置中的代码:

  <system.net>
  <mailSettings>
  <smtp from="from@gmail.com">
  <network host="smtp.gmail.com" defaultCredentials="false" password="password" port="587" enableSsl="true" />
  </smtp>
  </mailSettings>
  </system.net>

这是我在IdentityConfig.cs中的电子邮件服务课:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.
        SmtpClient client = new SmtpClient();
        return client.SendMailAsync("email from web config",
                                    message.Destination,
                                    message.Subject,
                                    message.Body);
     }
  }

这不会发送电子邮件,我不知道会有什么问题,希望有人可以提供帮助。

我以为您正在尝试做一些类似此帖子的方法,尝试使用asyncawait关键字(因为它是System.Threading.Tasks.Task方法),并且在using语句中包装SmtpClient以更轻松地管理IDisposable实例(请参阅如果您遇到所谓的TaskCanceledException):

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.
        using (SmtpClient client = new SmtpClient())
        {
            await client.SendMailAsync("email from web config",
                                        message.Destination,
                                        message.Subject,
                                        message.Body);
        }
    }
}

如果您不想使用using语句,则必须处理SmtpClient.SendCompleted事件以在发送邮件后手动处理SmtpClient实例:

public Task SendAsync(IdentityMessage message)
{
    // Plug in your email service here to send an email.
    SmtpClient client = new SmtpClient();
    // Registering SendCompleted event and dispose SmtpClient after sending message
    client.SendCompleted += (s, e) => {
        client.Dispose();
    };
    return client.SendMailAsync("email from web config",
                                message.Destination,
                                message.Subject,
                                message.Body);
}

最新更新