我正在在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);
}
}
这不会发送电子邮件,我不知道会有什么问题,希望有人可以提供帮助。
我以为您正在尝试做一些类似此帖子的方法,尝试使用async
和await
关键字(因为它是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);
}