Visual Studio .NET - mail sending code in windows application

Asked By Sharad Chandra on 15-Sep-11 04:46 AM
Hi all,
        I am developing a email sending application. i want a code in c# for sending mail in windows application.
        pls help me...
                  Thank you.
smr replied to Sharad Chandra on 15-Sep-11 04:49 AM
HI

try this

MailMessage message = new MailMessage();
 
message.From = new MailAddress("sender@foo.bar.com");
 
  
 
message.To.Add(new MailAddress("recipient1@foo.bar.com"));
 
message.To.Add(new MailAddress("recipient2@foo.bar.com"));
 
message.To.Add(new MailAddress("recipient3@foo.bar.com"));
 
  
 
message.CC.Add(new MailAddress("carboncopy@foo.bar.com"));
 
message.Subject = "This is my subject";
 
message.Body = "This is the content";
 
  
 
SmtpClient client = new SmtpClient();
 
client.Send(message);
 
  
 
System.Net.Mail reads SMTP configuration data out of the standard .NET configuration system (so for ASP.NET applications you’d configure this in your application’s web.config file).  Here is an example of how to configure it:
 
  
 
  <system.net>
 
  <mailSettings>
 
    <smtp from="test@foo.com">
 
    <network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" />
 
    </smtp>
 
  </mailSettings>
 
  </system.net>


refer links also
http://www.4guysfromrolla.com/articles/072606-1.aspx
http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx
Web Star replied to Sharad Chandra on 15-Sep-11 04:51 AM
Here is complete example of sending email from window application
  • http://www.codeproject.com/KB/cs/Sending_Mails_From_C_/SendMail.zip

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==http://www.codeproject.com/KB/cs/%3Cspan)

{

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();

}

}

}
Reena Jain replied to Sharad Chandra on 15-Sep-11 05:03 AM
hi,

The SmtpMail class can be used to send mails from your VB application. Mail is by default queued on the system, ensuring that the calling program does not block network traffic. The SmtpMail class is defined in the namespace System.Web.Mail. You need to call
Imports System.Web.Mail

before you use SmtpMail. This class has only one member function Send. Send sends a mail message. The Send method is overloaded. Either a MailMessage class or four arguments can be passed to the Send message. You can call the Send method in two manners:
SmtpMail.Send(txtFrom.Text, txtTo.Text, txtSubject.Text, txtMessage.Text)
Or, if you don't want to call System.Web.Util.
System.Web.Mail.SmptMail.Send(fromString, toString, SubjeOfTheMailString, MessageOfTheMailString)

You can call the Send method in two ways.

1. By passing MailMessage as a parameter,

public static void Send(MailMessage).

Here MailMessage is a class.
Private
mailMsg As MailMessage = New MailMessage()
Private mailMsg.From = from@fromServer.com
Private mailMsg.To = to@toServer.com
Private mailMsg.Cc = cc@ccServer.com"
Private mailMsg.Bcc = bcc@bccServer.com
Private mailMsg.Subject = "SubjectOfTheMailString"
Private mailMsg.Body = "BodyOfTheMailString"
SmtpMail.Send(mailMsg).

2. Direct method.
public static void Send(String from, String to, String subject, String messageText).

Hope this will help you
dipa ahuja replied to Sharad Chandra on 15-Sep-11 07:02 AM
Untitled document
using System.Net.Mail;
using System.Net;
 
private void button1_Click(object sender, EventArgs e)
     {
       string Sendto = "abc@gmail.com"; //Email Address to reciever
       string UserName = ""; //Ur Gmail address
       string PassWord = ""; //Gmail password
       NetworkCredential loginInfo = new NetworkCredential(UserName, PassWord);
       MailMessage msg = new MailMessage();
       msg.From = new MailAddress(UserName);
       msg.To.Add(new MailAddress(to.ToString()));
       msg.Subject = "Testing Mail";
       msg.Body = textBox1.Text.ToString();
       msg.IsBodyHtml = true;
       SmtpClient client = new SmtpClient("smtp.gmail.com");
       client.EnableSsl = true;
       client.UseDefaultCredentials = false;
       client.Credentials = loginInfo;
       client.Send(msg);
 
       MessageBox.Show("mail sent");
     }