Please enable Javascript for better experience...
Send Email code in C#
By Big | Feb 18, 2015 | In Articles | Total Views [ 1938 ]
Taged In
(2 Like)
Rate

This example explains how to send emails to users from code. Example using windows form and C# as platform. You can use this code and implement it in any platform for your use.

Introduction

Sending mails from code behind is very easy to implement in your project. In this example you will see how to do this.

You can use smtp as smtp.gmail.com, port number 587 and your creadentials as username and password to set gmail as your smtp provider.

Using the Code

Let's start with UI first. Below is the UI and is taking basic info.

UI design

Name "From textbox" as txtFrom, "To textbox" as txtTo, "subject textbox" as txtsubject, "Body textbox" as txtBody and "Send button" as btnSend in your page.

Code behind

Paste the below code in code behind. Add reference to System.Configuration dll in your project.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

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

namespace DotNetConceptMailSender
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtTo.Text) && !string.IsNullOrWhiteSpace(txtFrom.Text) && !string.IsNullOrWhiteSpace(txtSubject.Text) && !string.IsNullOrWhiteSpace(txtBody.Text))
            {
                SendMail(txtFrom.Text.Trim(), txtTo.Text.Trim(), "Test", txtSubject.Text, txtBody.Text);
            }
            else
            {
                MessageBox.Show("Please enter valid input");
            }
        }
        public void SendMail(string fromId, string to, string fromName, string subject, string body)
        {
            try
            {
                string host = ConfigurationManager.AppSettings["SMTPHost"].ToString();
                string userName = ConfigurationManager.AppSettings["SMTPUserName"].ToString();
                string pwd = ConfigurationManager.AppSettings["SMTPPassword"].ToString();
                string ssl = ConfigurationManager.AppSettings["SSL"].ToString();
                string portNo = ConfigurationManager.AppSettings["SMTPPort"].ToString();
                int port = Convert.ToInt32(portNo);

                MailMessage message = new MailMessage();
                SmtpClient Smtp = new SmtpClient();


                Smtp.Host = host;
                Smtp.Credentials = new System.Net.NetworkCredential(userName, pwd);
                Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                Smtp.Port = port;
                message.From = new MailAddress(fromId.Trim(), fromName);
                string[] toAddress = to.Split(',');
                foreach (object o in toAddress)
                {
                    message.To.Add(o.ToString().Trim());
                }
                message.Subject = subject;
                message.Body = body;

                message.IsBodyHtml = true;
                message.Priority = MailPriority.Normal;
                Smtp.Send(message);

            }
            catch(Exception ex)
            {
                MessageBox.Show("Sorry mail was not send. Please try again. "+ ex.Message);
            }
        }
    }
}

App.config

Replace App.config code with below lines. Replace smtp setting with your own settings or use gmail or yahoo details.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
<appSettings>
  <add key="SMTPHost" value="mail.yourdomain.com"/>
    <add key="SMTPUserName" value="username@yourdomain.com"/>
    <add key="SMTPPassword" value="password"/>
    <add key="SSL" value="false"/>
    <add key="SMTPPort" value="25"/>
</appSettings>
</configuration>

Run and try to send your first email

Share this

About the Author

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment