C# – Simple Email Service

This is just a quick snippet for sending emails using standard .NET/C# components. Here, I assume that FTP server is already configured or you have the details.

/* EmailService.cs */
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySampleProject
{
    public class EmailService
    {
        public void SendEmail(string body)
        {

            System.Net.Mail.MailMessage oMailMsg = new System.Net.Mail.MailMessage();
            oMailMsg.To.Add(ConfigurationManager.AppSettings["ToEmailAddress"]);
            oMailMsg.Subject = ConfigurationManager.AppSettings["Subject"];

            oMailMsg.IsBodyHtml = true;
            oMailMsg.Body = body;

            System.Net.Mail.SmtpClient oSMTPClient = new System.Net.Mail.SmtpClient();
            oSMTPClient.Send(oMailMsg);
            

        }
    }
}

The standard SmtpClient will look for smtp settings in the web.config/app.config.

<system.net>
 <mailSettings>
 <smtp from="[email protected]">
 <network host="localhost" password="" userName=""/>
 </smtp>
 </mailSettings>
 </system.net>

Also, it is best practise to add ‘To’ email address and ‘Subject’ in config settings, for deploying code in different enviornments (QA / Staging / Production)

<appSettings>
 <add key="ToEmailAddress" value="[email protected]"/>

 <add key="Subject" value="Some one has sent an email using website...Amazaing!"/>
 </appSettings>

 

Cheers!

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.