Free Web Development Online Tutorials, Learn to Code
Learn Aspx, Free Tutorial in C#, Web Application Development Guide

Send an email in c#

Let’s learn how to send email in application, below we have provided all details step by step


Step 1: Create a form like above form, You can add all other fields like Subject, CC, BCC etc. now we have removed all those fields, so you can understand the core mail sending functionality

@using (Html.BeginForm("sendmail", FormMethod.Post))            
    <input type="text" id="txtEmail" class="form-control" />
    <textarea id="txtContent" class="form-control"></textarea>
    <div style="text-align: center;">
    <input type="submit" value="Send Email" class="btn btn-success"/>

Set SMTP details in web.config

Step 2: Add your SMTP details in web.config file, it will be good if keep configuration details in a separate File, and read the file using configuration framework

Set MailMessage in C# code for sending email

Step 3: Now create a utility class with some name, here we have created WTRMail, inside that create a method called SendMail() with two object MailMessage and SmtpClient

public class WTRMail
        MailMessage objMail = new MailMessage(MFrom, MTo, MSubject, MBody);
        //Default setting
        objMail.Priority = MailPriority.Normal;
        objMail.IsBodyHtml = this.IsHtmlBody;
        objMail.ReplyTo = new MailAddress(this.ReplyTo);

Read SMTP info from web.config

Step 4: Read all your SMTP configuration information from web.config or configuration framework object

public class WTRMail            
string _SmtpServer= ConfigurationManager.AppSettings["SmtpServer"];
string _SmtpUserName= ConfigurationManager.AppSettings["SmtpUserName"];
string _SmtpPassword= ConfigurationManager.AppSettings["SmtpPassword"];
string _SMTPPort= ConfigurationManager.AppSettings["SMTPPort"];           
    private bool SendETMail()
        SmtpClient objSmtp = new SmtpClient();
        objSmtp.EnableSsl = false ;
        objSmtp.Host = _SmtpServer;
        objSmtp.Port = _SMTPPort;
        objSmtp.Credentials = new System.Net.NetworkCredential(_SmtpUserName, _SmtpPassword);

In above code you can see how we read the SMTP information from web.config file, then created a new instance of SmtpClient class, then set server, port, credentials and finally executed the send method