Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Sending Emails from C# Application using default SMTP

0.00/5 (No votes)
21 Sep 2004 1  
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.

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;

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

Complete Source Code

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=="mailto:test@mail.com">test@mail.com)

{

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here