dotnet core 2.0中appSettings.json中的SMTP设置

时间:2019-02-21 09:57:20

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

在Asp.net中,我通常可以使用以下代码发送电子邮件:

using (var smtp = new SmtpClient())
{
    await smtp.SendMailAsync(mailMessage);
}

在web.config中提供了smtp设置后,SmtpClient会自动使用它们。 web.config配置部分如下所示:

<mailSettings>
    <smtp deliveryMethod="Network">
      <network host="myHost" port="25" userName="myUsername" password="myPassword" defaultCredentials="false" />
    </smtp>
</mailSettings>

是否可以在dotnet core 2.0应用程序的appSettings.json文件中进行配置,然后SmtpClient才能使用它,类似于Asp.net?

2 个答案:

答案 0 :(得分:1)

如果您坚持使用System.Net.Mail.SmtpClient,则可以通过以下方式做到这一点:

appsettings.json

{
  "Smtp": {
    "Server": "mail.whatever.com",
    "Port": 25,
    "FromAddress": "yourfromemail@whatever.com"
  },
}

代码:

    public async Task SendEmailAsync(string email, string subject, string htmlMessage)
    {
        MailMessage message = new MailMessage();
        message.Subject = subject;
        message.Body = htmlMessage;
        message.IsBodyHtml = true;
        message.To.Add(email);

        string host = _config.GetValue<string>("Smtp:Server", "defaultmailserver");
        int port = _config.GetValue<int>("Smtp:Port", 25);
        string fromAddress = _config.GetValue<string>("Smtp:FromAddress", "defaultfromaddress");

        message.From = new MailAddress(fromAddress);

        using (var smtpClient = new SmtpClient(host, port))
        {
            await smtpClient.SendMailAsync(message);
        }
    }

_configIConfiguration的实现,它被注入到SendEmailAsync方法所在的类中。

但是,由于它已经过时,因此最好探索上面评论中提到的其他方法。

答案 1 :(得分:1)

您可能想要实现的目标是这样的:

文件: appsettings.json(定义数据的位置)

{
    ...
    "EmailSettings": {
        "From": "no-reply@example.com",
        "Username": "username",
        "Password": "password",
        "Host": "smtp.example.com",
        "Port": 25
    },
    ...
}

文件: Email.cs(您在其中定义将包含数据的模型)

public class EmailSettings
{
    public string From { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string Host { get; set; }
    public int Port { get; set; }
}

文件: Startup.cs(将数据绑定到将随处可用的模型)

public void ConfigureServices(IServiceCollection services)
{              
   ...

     services.AddConfiguration<EmailSettings>(Configuration, "EmailSettings");

   ...
}

文件: Email.cs(您在其中定义如何发送邮件)

public class EmailService
{
    private readonly EmailSettings _mailSettings;
    public EmailService(EmailSettings mailSettings)
    {
        _mailSettings = mailSettings;
    }

    public async Task<bool> SendMail(MailRequest mailRequest)
    {
        //Here goes your code to send a message using "_mailSettings" like:
        // _mailSettings.From
        // _mailSettings.Port
        //ect...
    }
}

为此,请打开this tutorial,然后转到名为“ #6 AppSettings – PRE-Binding ”的方式6。

您将找到使这项工作不同的方法,但强烈建议使用第六种方法