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="no-reply@mydomain.com">
 <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="me@mydomain.com"/>

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

 

Cheers!

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s