Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send email with .NET Core 2.2

In MVC ASP.NET you can set the smtp configuration in the web.config file like this :

<system.net>
    <mailSettings>
        <smtp from="MyEmailAddress" deliveryMethod="Network">
            <network host="smtp.MyHost.com" port="25" />
        </smtp>
    </mailSettings>
</system.net>

And this works perfectly.

But I can't get it to work in .NET Core 2.2 because there you have a appsettings.json file.

I have this :

"Smtp": {
    "Server": "smtp.MyHost.com",
    "Port": 25,
    "FromAddress": "MyEmailAddress"
}

When sending a mail it shows this error message :

enter image description here

like image 868
user7849697 Avatar asked Nov 06 '19 12:11

user7849697


Video Answer


1 Answers

You could use Options with DI in your email sender,refer to

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.Startup ConfigureServices

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.Access the SmtpSettings using Options by DI wherever you need.

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;
    }
}
like image 180
Ryan Avatar answered Sep 27 '22 22:09

Ryan