Click here to Skip to main content
6,596,602 members and growing! (19,616 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate License: The Code Project Open License (CPOL)

Sending Emails from C# Application using default SMTP

By Rajan2may

Sending Mails from C# using System.Web.Mail using default SMTP
C#, VB 6, Windows, .NET 1.1VS.NET2003, Dev
Posted:13 Sep 2004
Updated:21 Sep 2004
Views:85,468
Bookmarked:37 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
19 votes for this article.
Popularity: 2.82 Rating: 2.21 out of 5
11 votes, 57.9%
1
1 vote, 5.3%
2
1 vote, 5.3%
3
1 vote, 5.3%
4
5 votes, 26.3%
5

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rajan2may


Member
Working as Consultant with Merrill Lynch, New York
Occupation: Web Developer
Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
GeneralGetting Error Pinmembersansar1:24 15 Feb '08  
GeneralKay says there's a potential bug PinadminSean Ewington9:55 4 Jun '07  
Generalhi Pinmemberazmiralda124:17 28 Dec '06  
GeneralSMTP username/password Pinmembershabonaa11:48 1 Dec '06  
GeneralSMTP PinmemberGKT13:44 19 May '06  
GeneralCan not access CDO.Message Pinmembercanhga0:09 19 Sep '05  
GeneralRe: Can not access CDO.Message Pinmemberanzac11:40 5 Dec '05  
GeneralRe: Not robust enough PinmemberRajan2May18:59 14 Sep '04  
GeneralXP Home Pinmembermxmissile10:48 14 Sep '04  
GeneralRe: XP Home PinprotectorHeath Stewart11:42 21 Sep '04  
GeneralNot robust enough Pinmembermav.northwind21:42 13 Sep '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 21 Sep 2004
Editor: Sean Ewington
Copyright 2004 by Rajan2may
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project