How to configure SMTP settings in web.config

By setting the values <mailSettings> section of the in the web.config you can just new up an SmtpClient and the client will use those settings.

https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.-ctor?view=net-6.0#system-net-mail-smtpclient-ctor

Web.Config file:

<configuration>
 <system.net>
        <mailSettings>
            <smtp from="yourmail@gmail.com">
                <network host="smtp.gmail.com" 
                 port="587" 
                 userName="yourmail@gmail.com" 
                 password="yourpassword" 
                 enableSsl="true"/>
            </smtp>
        </mailSettings>
</system.net>
</configuration>

C#:

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);

However, if authentication is needed, I would suggest using a configuration provider that is more secure for usernames and passwords and settings them with a NetworkCredentials object.

C#:

SmtpClient smtpClient = 
    new SmtpClient(_configuration.SmtpHost, _configuration.SmtpPort);
smtpClient.Credentials = 
    new NetworkCredential(_configuration.EmailUsername, _configuration.EmailPassword)
smtpClient.Send(msgMail);

Leave a Comment

tech