There was a problem loading the comments.

Configuring Email in a .NET Application: Web.config & Code Implementation

Support Portal  »  Knowledgebase  »  Viewing Article

  Print

.NET Email Configuration: Web.config & Code

1. Web.config Email Settings

To enable email functionality in your .NET application, add the following SMTP settings in Web.config:

<configuration>
  <system.net>
    <mailSettings>
      <smtp>
        <network 
          host="smtp.yourserver.com" 
          port="587" 
          userName="your-email@example.com" 
          password="your-password" 
          enableSsl="true" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

 

2. Sending Emails in C#

Use the following C# code to send an email using the .NET Mail class:

using System;
using System.Net;
using System.Net.Mail;
using System.Configuration;

public class EmailService
{
    public void SendEmail(string recipientEmail, string emailBody)
    {
        string ourEmail = ConfigurationManager.AppSettings["OurEmail"];
        string smtpServer = ConfigurationManager.AppSettings["SMTPServer"];
        string emailPassword = ConfigurationManager.AppSettings["OurEmailPass"];

        MailMessage mail = new MailMessage
        {
            From = new MailAddress(ourEmail),
            Subject = "Message from mydomain.com",
            Body = emailBody,
            IsBodyHtml = false,
            Priority = MailPriority.High
        };

        mail.To.Add(new MailAddress(recipientEmail));

        SmtpClient smtp = new SmtpClient(smtpServer)
        {
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(ourEmail, emailPassword),
            EnableSsl = true
        };

        smtp.Send(mail);
    }
}

 

3. Troubleshooting Common Issues

  • Authentication Failure: Check your SMTP username and password.
  • Port Blocking: Use port 587 (TLS) or 465 (SSL) as per your provider.
  • Firewall Restrictions: Ensure outbound traffic on the SMTP port is allowed.

By following these steps, you can successfully integrate email functionality in your .NET application. 


Share via
Did you find this article useful?  

Related Articles

© Softsys Hosting