【问题标题】:Send email with .NET Core 2.2使用 .NET Core 2.2 发送电子邮件
【发布时间】:2020-03-02 23:07:17
【问题描述】:

在 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"
}

发送邮件时会显示此错误消息:

【问题讨论】:

  • 您必须将服务器和端口提供给您的 SmtpClient 实例的构造函数。 docs.microsoft.com/en-us/dotnet/api/…
  • 与 .NET 不同,.NET Core 不会自动读取将其设置应用于系统类的配置文件。您需要实际读取配置并使用它,通常是通过在您使用的任何依赖注入机制上应用一个方法。

标签: c# sendmail asp.net-core-2.2


【解决方案1】:

为了从appsettings.json 获取Smtp 设置,您可以使用

public class SmtpSettings{
  public string Server {get;set;}
  public int Port {get;set;}
  public string FromAddress {get;set}
}

var smtpSettings = Configuration.GetSection("Smtp").Bind(smtpSettings);

现在您已经有了 smtp 设置,您可以在 SmtpClient() 中使用它们

 using (var client = new SmtpClient()){
    {
        await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, true);
    }
 }

【讨论】:

  • SmtpSettings smtpSettings; smtpSettings = Configuration.GetSection("Smtp").Bind(smtpSettings);
  • 停止对知名类使用 var
【解决方案2】:

您可以在您的电子邮件发件人中使用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();
    }
}

4. 使用Options 由 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;
    }
}

【讨论】:

    【解决方案3】:

    要从 appsettings.json 获取 SMTP 设置,请按照步骤操作,

    1. appsettings.json 值,
       "EmailSettings": {
        "EmailSettings": {
        "MailServer": "smtp.gmail.com",
        "MailPort": 587,
        "SenderName": "Sender Name",
        "SenderEmail": "preferred email",
        "UserName": "username",
        "Password": "password",
        "EnableSsl": "true", /// if you need it use
        "EmailKey": "EmailKey" /// if you need it use
      }
    
    1. 定义电子邮件凭据的属性,

      public void ConfigureServices(IServiceCollection services)
      {
        services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
      }
      

    3.类属性,

        public class EmailSettings
        {
            public string MailServer { get; set; }
            public int MailPort { get; set; }
            public string SenderName { get; set; }
            public string SenderEmail { get; set; }
            public string Password { get; set; }
            public bool EnableSsl { get; set; }
            public string EmailKey { get; set; }
        }
    
    1. 来电者,
    var emailResult = SendEmail(loginName, Message, subject, "User Creation");
    

    5.获取并设置值,

            public async Task<IActionResult> SendEmail(string email, string Message, string Subject, string EmailType, string HTMLMessageContent = "")
            {
                HTMLMessageContent = Message;
                EmailLog emailModel = new EmailLog
                {
                    EmailType = EmailType,
                    Subject = Subject,
                    EmailContent = Message,
                    FromEmail = _emailSettings.SenderEmail,
                    ToEmails = email,
                    CreatedBy = sessionData != null ? sessionData.ApplicationUserId : "",
                    OrganizationId = sessionData != null ? sessionData.OrganizationId : 0
    
                };
    
               var from = new EmailAddress(_emailSettings.SenderEmail, _emailSettings.SenderName);
                var to = new EmailAddress(email, "");
                var msg = MailHelper.CreateSingleEmail(from, to, Subject, Message, HTMLMessageContent);
                var response = await client.SendEmailAsync(msg); 
                return Ok("Success");
            }
    

    最后,将电子邮件发送给相关人员。代码酷..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2021-01-30
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2020-09-22
      相关资源
      最近更新 更多