6

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

user7849697
  • 503
  • 1
  • 8
  • 19
  • You have to give the server and port into the constructor of your SmtpClient instance. https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.-ctor?view=netcore-2.2 – Alexander Powolozki Nov 06 '19 at 12:55
  • 1
    Unlike .NET, .NET Core doesn't automagically read configuration files that have their settings applied to system classes. You'll need to actually read the configuration and use it, typically by applying a method on whatever dependency injection mechanism you're using. – Jeroen Mostert Nov 06 '19 at 12:55

3 Answers3

10

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;
    }
}
Ryan
  • 19,118
  • 10
  • 37
  • 53
5

In order to get the SMTP settings from appsettings.json, follow steps,

  1. appsettings.json values,
   "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. define the properties for email credentials,

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

3.class properties,

    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. caller,
var emailResult = SendEmail(loginName, Message, subject, "User Creation");

5.get & set the values,

        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");
        }

Finally, the email send to concern person. Code Cool..

Prakash CS
  • 199
  • 1
  • 8
3

In order to get the Smtp settings from appsettings.json you can use

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);

Now that you have the smtp settings you can use them in the SmtpClient()

 using (var client = new SmtpClient()){
    {
        await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, true);
    }
 }
HariHaran
  • 3,642
  • 2
  • 16
  • 33