Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / Visual Basic
Article

Sending Emails from C# Application using default SMTP

Rate me:
Please Sign up or sign in to vote.
2.60/5 (25 votes)
21 Sep 2004CPOL 238.8K   13K   52   17
Sending Mails from C# using System.Web.Mail using default SMTP

Screenshot - SendMail.jpg

Introduction

This article is provide a demo for how we can send Emails from a C# Windows Application.

Description

First add the reference from project-->Add References then select System.Web.dll. Then include using System.Web.Mail in your class and create MailMessage object and assign values to all required properties.

MailMessage objMsg=new MailMessage();

if(ValidateEmail(txtTo.Text)==true) objMsg.To=txtTo.Text;

else throw new MyExp();

objMsg.From=sFrom;

if (txtCc.Text!="") objMsg.Bcc=txtBcc.Text;

if (txtBcc.Text!="") objMsg.Cc=txtCc.Text;

if (txtSubject.Text!="") objMsg.Subject=txtSubject.Text;

else throw new MyExp();

objMsg.Body=txtMessage.Text;

You can send attachments also with your mails. For that we can use MailAttachment Object like :

MailAttachment attach1;
string sFile;
if(lstfiles.Items.Count>0)
{
    for(int i=0;i<lstfiles.Items.Count;i++)
    {
        lstfiles.SelectedIndex=i;
        sFile=lstfiles.Text;
        attach1=new MailAttachment(sFile);
        objMsg.Attachments.Add(attach1);
    }
}

But before sending the mail you have to set From field by clicking From Button and Smtp Server, if you are using it on Windows 2000, Windows XP Professional, Windows Server 2003 and have a configured smtp server then you can leave it blank.

Image 2

Then you can send the mail by clicking Send Button.

SmtpMail.Send(objMsg); 

Also when you run this application it will show in System tray and when you right click on that icon it will show the popup menu.

mymenu=new ContextMenu();

mymenu.MenuItems.Add("Open",new System.EventHandler(open_Click));

mymenu.MenuItems.Add("Hide",new System.EventHandler(hide_Click));

mymenu.MenuItems.Add("Exit",new System.EventHandler(exit_Click));

myIcon=new NotifyIcon();

myIcon.Text="Right Click For Context Menu";

myIcon.Visible=true;

myIcon.Icon=new Icon(GetType(),"MAIL6.ICO");

myIcon.ContextMenu=mymenu;

Image 3

This above image show the popup at System tray, from where we can Hide,Open and Exit the Application.

Complete Source Code

C#
using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Web.Mail;

using System.Text.RegularExpressions;

using MailOpt;

namespace MailTest

{

public class SendMail : System.Windows.Forms.Form

{

    private System.Windows.Forms.TextBox txtBcc;

    private System.Windows.Forms.Label label1;

    private System.Windows.Forms.Label label2;

    private System.Windows.Forms.Label label3;

    private System.Windows.Forms.Label label4;

    private System.Windows.Forms.Label label5;

    private System.Windows.Forms.Label label6;

    private System.Windows.Forms.Button button3;

    private System.Windows.Forms.Label label7;

    private System.Windows.Forms.OpenFileDialog dlgopenFile;

    private System.Windows.Forms.Button btnshowfile;

    private System.Windows.Forms.TextBox txtAttachment;

    private System.Windows.Forms.TextBox txtTo;

    private System.Windows.Forms.TextBox txtSubject;

    private System.Windows.Forms.TextBox txtCc;

    private System.Windows.Forms.RichTextBox txtMessage;

    private System.Windows.Forms.ListBox lstfiles;

    private System.Windows.Forms.Button btnSend;

    int c=0;

    public static string sFrom="";

    public static string sSmtpServer="";

    private System.Windows.Forms.Button btnFrom;

    NotifyIcon myIcon;

    ContextMenu mymenu;

    private System.ComponentModel.Container components = null;

    public SendMail()

    {

    InitializeComponent();

    }

    protected override void Dispose( bool disposing )

    {

        if( disposing )

        {

            if(disposing)

            {

                this.myIcon.Dispose();

            }

            if (components != null) 

            {

                components.Dispose();

            }

        }

            base.Dispose( disposing );


    }    

    [STAThread]

    static void Main() 

    {

        Application.Run(new SendMail());

    }

    private void btnSend_Click(object sender, System.EventArgs e)

    {

    try

    {

    if (sSmtpServer=="")

    {

    MessageBox.Show("You have not set any SmtpServer name! It will " & _
"use default Mail Server if you configured on your machine","SmtpServer Name Not Found",
MessageBoxButtons.OK,MessageBoxIcon.Information);

btnFrom.Focus();

}

else

{

SmtpMail.SmtpServer=sSmtpServer;

}

if(sFrom=="" || sFrom==<a href="mailto:test@mail.com">test@mail.com</a>)

{

MessageBox.Show("Please set your (Sender's) Address First","Sender Address",
MessageBoxButtons.OK,MessageBoxIcon.Error);

btnFrom.Focus();

return;

}


MailMessage objMsg=new MailMessage();

if(ValidateEmail(txtTo.Text)==true) objMsg.To=txtTo.Text;

else throw new MyExp();

objMsg.From=sFrom;

if (txtCc.Text!="") objMsg.Bcc=txtBcc.Text;

if (txtBcc.Text!="") objMsg.Cc=txtCc.Text;

if (txtSubject.Text!="") objMsg.Subject=txtSubject.Text;

else throw new MyExp();

objMsg.Body=txtMessage.Text;

MailAttachment attach1;//, attach2, attach3;

string sFile;

if(lstfiles.Items.Count>0)

{

for(int i=0;i<lstfiles.Items.Count;i++)

{

lstfiles.SelectedIndex=i;

sFile=lstfiles.Text;

attach1=new MailAttachment(sFile);

objMsg.Attachments.Add(attach1);

}

}

SmtpMail.Send(objMsg); 

lstfiles.Items.Clear();

MessageBox.Show("Mail Sent");

}

catch(Exception ex)

{

MessageBox.Show("Error :"+ex.ToString()); 

}

}

private void btnshowfile_Click(object sender, System.EventArgs e)

{

dlgopenFile.ShowDialog();

txtAttachment.Text=dlgopenFile.FileName;

lstfiles.Items.Add (txtAttachment.Text);

}

private void button3_Click(object sender, System.EventArgs e)

{

Environment.Exit(0);

}

private void SendMail_Load(object sender, System.EventArgs e)

{

mymenu=new ContextMenu();

mymenu.MenuItems.Add("Open",new System.EventHandler(open_Click));

mymenu.MenuItems.Add("Hide",new System.EventHandler(hide_Click));

mymenu.MenuItems.Add("Exit",new System.EventHandler(exit_Click));

myIcon=new NotifyIcon();

myIcon.Text="Right Click For Context Menu";

myIcon.Visible=true;

myIcon.Icon=new Icon(GetType(),"MAIL6.ICO");

myIcon.ContextMenu=mymenu;

}

protected void exit_Click(Object sender, System.EventArgs e) 

{

Close();

}

protected void hide_Click(Object sender, System.EventArgs e) 

{

Hide();

}

protected void open_Click(Object sender, System.EventArgs e) 

{

Show();

}


public bool ValidateEmail(string sEmail)

{

Regex exp=new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

Match m=exp.Match(sEmail);

if(m.Success && m.Value.Equals(sEmail)) return true;

else return false;

}


private void btnFrom_Click(object sender, System.EventArgs e)

{

MailOpt.frmFrom frm=new MailOpt.frmFrom();

frm.Show();

}

}

class MyExp: Exception

{

public override string ToString()

{

return " Value is Blank or Invalid";

}

}

}


//Other frmForm.cs


using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using MailTest;

namespace MailOpt

{

public class frmFrom : System.Windows.Forms.Form

{

private System.Windows.Forms.TextBox txtFrom;

private System.Windows.Forms.Label label1;

private System.Windows.Forms.Button btnok;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.TextBox txtSmtpServer;

private System.Windows.Forms.Label label2;

private System.ComponentModel.Container components = null;

public frmFrom()

{

InitializeComponent();

}

protected override void Dispose( bool disposing )

{

if( disposing )

{

if(components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}


#region Windows Form Designer generated code

#endregion

private void btnok_Click(object sender, System.EventArgs e)

{

SendMail.sFrom=txtFrom.Text;

SendMail.sSmtpServer=txtSmtpServer.Text;

Dispose();

}

private void button1_Click(object sender, System.EventArgs e)

{

Dispose();

}

}

}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Working as Consultant with Merrill Lynch, New York

Comments and Discussions

 
Questionhow to know my smtp server Pin
Member 1022082129-Sep-13 10:45
Member 1022082129-Sep-13 10:45 
QuestionEmail from C# program Pin
boss prabu19-Mar-13 7:51
boss prabu19-Mar-13 7:51 
QuestionWhat is MailOpt? Pin
trantoan6710-Oct-12 8:01
trantoan6710-Oct-12 8:01 
QuestionSending Emails from C# Application using default SMTP Pin
Wosu30-May-12 3:51
Wosu30-May-12 3:51 
QuestionEmail Component Pin
Gregory Nozik28-Sep-11 15:00
Gregory Nozik28-Sep-11 15:00 
GeneralMy vote of 4 Pin
jorge acevedo16-Aug-10 4:00
jorge acevedo16-Aug-10 4:00 
GeneralGetting Error Pin
sansar15-Feb-08 0:24
sansar15-Feb-08 0:24 
GeneralKay says there's a potential bug Pin
Sean Ewington4-Jun-07 8:55
staffSean Ewington4-Jun-07 8:55 
Generalhi Pin
azmiralda1228-Dec-06 3:17
azmiralda1228-Dec-06 3:17 
GeneralSMTP username/password Pin
shabonaa1-Dec-06 10:48
shabonaa1-Dec-06 10:48 
GeneralSMTP Pin
GKT19-May-06 12:44
GKT19-May-06 12:44 
QuestionCan not access CDO.Message Pin
canhga18-Sep-05 23:09
canhga18-Sep-05 23:09 
AnswerRe: Can not access CDO.Message Pin
anzac5-Dec-05 10:40
anzac5-Dec-05 10:40 
GeneralRe: Not robust enough Pin
Rajan2may14-Sep-04 17:59
Rajan2may14-Sep-04 17:59 
GeneralXP Home Pin
mxmissile14-Sep-04 9:48
mxmissile14-Sep-04 9:48 
GeneralRe: XP Home Pin
Heath Stewart21-Sep-04 10:42
protectorHeath Stewart21-Sep-04 10:42 
GeneralNot robust enough Pin
mav.northwind13-Sep-04 20:42
mav.northwind13-Sep-04 20:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.