c# - 使用 .NET Core 2.2 发送电子邮件
问题描述
在 MVC ASP.NET 中,您可以像这样在 web.config 文件中设置 smtp 配置:
<system.net>
<mailSettings>
<smtp from="MyEmailAddress" deliveryMethod="Network">
<network host="smtp.MyHost.com" port="25" />
</smtp>
</mailSettings>
</system.net>
这非常有效。
但我无法让它在 .NET Core 2.2 中工作,因为你有一个 appsettings.json 文件。
我有这个 :
"Smtp": {
"Server": "smtp.MyHost.com",
"Port": 25,
"FromAddress": "MyEmailAddress"
}
发送邮件时显示此错误消息:
解决方案
您可以Options
在您的电子邮件发件人中使用 DI,请参阅
https://kenhaggerty.com/articles/article/aspnet-core-22-smtp-emailsender-implementation
1.appsettings.json
"Smtp": {
"Server": "smtp.MyHost.com",
"Port": 25,
"FromAddress": "MyEmailAddress"
}
2.SmtpSettings.cs
public class SmtpSettings
{
public string Server { get; set; }
public int Port { get; set; }
public string FromAddress { get; set; }
}
3.启动配置服务
public class Startup
{
IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SmtpSettings>(Configuration.GetSection("Smtp"));
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
}
Options
4.在任何需要的地方使用 DI访问 SmtpSettings 。
public class EmailSender : IEmailSender
{
private readonly SmtpSettings _smtpSettings;
public EmailSender(IOptions<SmtpSettings> smtpSettings)
{
_smtpSettings = smtpSettings.Value;
}
public Task SendEmailAsync(string email, string subject, string message)
{
var from = _smtpSettings.FromAddress;
//other logic
using (var client = new SmtpClient())
{
{
await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, true);
}
}
return Task.CompletedTask;
}
}
推荐阅读
- java - 如何序列化其方法具有多个参数的对象
- javascript - Sequelize Seeding ARRAY(ENUM)
- windows - 如何在 Windows 上将数据导入 MongoDB.Atlas
- sql - 如何在同一行中不同数据的乘积的 SQL 表中创建 URL
- java - 2个线程要执行同一个对象,会出现什么问题?
- vba - Powerpoint - VBA - 幻灯片状态
- java - NavigationComponents - 导航抽屉不导航
- browser - Web 应用程序切换浏览器
- c++ - 为什么 std:: 符号在共享库中被强制导出?
- selenium - 使用 Selenium IDE 和 WebDriver 编写的测试执行时间比较