gpt4 book ai didi

c# - 实现 SendEmailAsync 接口(interface)并发送邮件

转载 作者:太空狗 更新时间:2023-10-29 23:29:08 27 4
gpt4 key购买 nike

我不知道如何调用 SendEmailAsync 函数

注册帖子页面

public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
$"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}

// If we got this far, something failed, redisplay form
return View(model);
}

邮件配置页面

//这段代码已经存在

    public interface IEmailSender
{
Task SendEmailAsync(string email, string subject, string message);
}

//我从其他网站获得了这段代码。我不知道如何一起使用它。

public class sendMail : IEmailSender // this line is written by me
{
public async Task SendEmailAsync(string email, string subject, string message)
{
var emailMessage = new MimeMessage();

emailMessage.From.Add(new MailboxAddress("Joe Bloggs", "jbloggs@example.com"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("plain") { Text = message };

using (var client = new SmtpClient())
{
client.LocalDomain = "some.domain.com";
await client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false);
await client.SendAsync(emailMessage).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
}

如何编写类定义来发送电子邮件。

断点没有到达这里,我认为我的实现有问题。

最佳答案

在 Startup 中确保你改变了这个:

services.AddTransient<IEmailSender, AuthMessageSender>();

services.AddTransient<IEmailSender, sendMail>();

这样你的实现就会被注入(inject)

关于c# - 实现 SendEmailAsync 接口(interface)并发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41485101/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com