ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,jQuery Plugins,jQuery UI,SSRS,XML,HTML,jQuery demos,code snippet examples.

Breaking News

  1. Home
  2. E-mail
  3. Send E-mail using C Sharp

Send E-mail using C Sharp

Today email is a part of our modern life. We can’t think a day without email. Many companies are providing email service. Most of them are free. But for that we need to follow their terms and conditions. With the help of .Net Framework and C# we can easily build our own email service. This article explains how to send e-mail in C#. Summary of the article:
  • Prerequisite for E-mail Sending
  • UI Design for E-mail Sending
  • C# Code to Send E-mail
Prerequisite for E-mail Sending
In order to transfer or receive data over the internet Microsoft .NET framework provides two namespaces. One is System.Net and another one is System.Net.Sockets. In C# language the SMTP protocol is used to send email. C# use  System.Net.Mail namespace for sending email.
We need a SMTP server also. If we don’t have any SMTP, we  can use free SMTP server. We can also use our gmail account. At first we need to configure this SMTP server.
UI Design for E-mail Sending
If Microsoft Visual Studio is installed, Start it and select New Project from the file menu.
Design a graphical interface for email sending. A sample UI is given bellow:
C# Code to Send E-mail
Writhe the following C# code for email sending.
string Host = "Host IP of SMTP";
int Port = 25;

MailMessage mail = new MailMessage();

string to = txtMailTo.Text;
string from = txtMailFrom.Text;
string subject = txtMailSub.Text;
string body = txtMailBody.Text;
string mailCC = txtMailCC.Text;
string mailBCC = txtMailBCC.Text;

MailMessage message = new MailMessage(from, to, subject, body);
message.IsBodyHtml = true;

if (mailCC !="") message.CC.Add(mailCC);    // to add cc
if (mailBCC!="") message.Bcc.Add(mailBCC);  // to add bcc

// for attachment
if (txtAttachment.HasFile)
{
    string strFileName = System.IO.Path.GetFileName(txtAttachment.PostedFile.FileName);
    Attachment attachFile = new Attachment(txtAttachment.PostedFile.InputStream, strFileName);
    message.Attachments.Add(attachFile);
}

SmtpClient client = new SmtpClient(Host, Port);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(message);
Most of the enterprise applications have email facility to communicate with customers or clients. For that many developers uses different third party tools. But, third party tools are not always user friendly and they are difficult to customize. Some times they can arise security problems. With the help of this  tutorials anybody can easily develop his/her own email sending modules. And can integrate it with CRM system.

No comments