By Ravindra Sadaphule
Summary: This is a web
based smtp email program. This program can be used to send a email
through a SMTP server. User can specify SMTP server IP, sender's mail
address, recipient's email address and mail content. When the user
clicks on "send mail" button , mail is forwarded to SMTP
server which in turn forwards the mail to recepient.
Author: Ravindra Sadaphule is currently working as a
Programmer Analyst in Silverline Technologies, Mumbai . He has around 5.5 years
of software development experience. His skill includes ASP, VB 6.0, Javascript ,
MTS. His current interests are .NET & C# . He can be reached
at ravi_sadaphule@hotmail.com
.
Article
Details: This smtp mail program is for .net
beta 2 version . i have written a SMTP email component in C# and compiled it
into a dll. Then this dll is accessed through aspx file which can be viewed in
browser.
There is built in SMTP class
already available in System.Web.Mail namespace . However it is worth
taking a look at program below as it shows inner details of how to
communicate with SMTP server. Once u grasp this technique, u can
modify it communicate any tcp socket server like ftp(for file
access),http(for web access),IRC (for chat) etc.
First i am giving source of
SMTP mail client.
/******************SMTPMail.cs ************
Name : SMTPMail.cs
Description : SMTP email client .
Version : 1.0
Author : Ravindra Sadaphule
Email : ravi_sadaphule@hotmail.com
Last Modified: 13th September , 2001
To compile: csc /t:library /out:SMTPMail.dll
SMTPMail.cs
Note : save this file in c:/inetpub/wwwroot/bin
directory
*/
namespace
Ravindra
{
/* SMTPClient is a class which
inherits from TcpClient . Hence it can access all protected and public membert
of TcpClient
*/
public class SMTPClient :
System.Net.Sockets.TcpClient
{
public bool isConnected()
{
return Active ;
}
public void
SendCommandToServer(string Command)
{
System.Net.Sockets.NetworkStream ns =
this.GetStream() ;
byte[] WriteBuffer ;
WriteBuffer =
new byte[1024] ;
System.Text.ASCIIEncoding en =
new System.Text.ASCIIEncoding() ;
WriteBuffer =
en.GetBytes(Command) ;
ns.Write(WriteBuffer,0,WriteBuffer.Length);
return ;
}
public string
GetServerResponse()
{
int StreamSize ;
string ReturnValue = ""
;
byte[] ReadBuffer ;
System.Net.Sockets.NetworkStream ns = this.GetStream() ;
ReadBuffer = new byte[1024]
;
StreamSize =
ns.Read(ReadBuffer,0,ReadBuffer.Length);
if (StreamSize==0)
{
return
ReturnValue ;
}
else
{
System.Text.ASCIIEncoding en =
new System.Text.ASCIIEncoding() ;
ReturnValue =
en.GetString(ReadBuffer) ;
return ReturnValue;
}
}
public bool DoesStringContainSMTPCode(System.String
s,System.String
SMTPCode)
{
return
(s.IndexOf(SMTPCode,0,10)==-1)?false:true ;
}
}// end of class SMTPClient
public class SMTPMail
{
private System.String
_SMTPServerIP = "127.0.0.1" ;
private System.String _errmsg = ""
;
private System.String
_ServerResponse = "" ;
private System.String
_Identity = "expowin2k" ;
private System.String
_MailFrom =
"" ;
private System.String _MailTo = ""
;
private System.String
_MailData =
"" ;
private System.String _Subject = ""
;
public System.String Subject
// This property contains Subject of email
{
set
{
_Subject = value ;
}
}
public System.String Identity //
This property contains Sender's Identity
{
set
{
_Identity = value ;
}
}
public System.String MailFrom //
This property contains sender's email address
{
set
{
_MailFrom = value ;
}
}
public System.String MailTo //
This property contains recepient's email address
{
set
{
_MailTo = value ;
}
}
public System.String
MailData // This property contains email message
{
set
{
_MailData = value ;
}
}
public
System.String SMTPServerIP // This property contains of SMTP server IP
{
get
{
return
_SMTPServerIP ;
}
set
{
_SMTPServerIP =
value ;
}
}
public System.String ErrorMessage
// This property contais error message
{
get
{
return _errmsg ;
}
}
public
System.String ServerResponse // This property contains server response
{
get
{
return _ServerResponse ;
}
}
public void SendMail()
{
try
{
System.String ServerResponse
;
SMTPClient tcp = new
SMTPClient() ;
tcp.Connect(SMTPServerIP,25)
;// first connect to smtp server
bool blnConnect =
tcp.isConnected();
// test for successful
connection
if (!blnConnect)
{
_errmsg = "Connetion
Failed..." ;
return;
}
//read response of the
server
ServerResponse =
tcp.GetServerResponse() ;
if
(tcp.DoesStringContainSMTPCode(ServerResponse,"220"))
{
_ServerResponse +=
ServerResponse ;
}
else
{
_errmsg = "connection
failed" + ServerResponse ;
return ;
}
System.String[] SendBuffer = new System.String[6] ;;
System.String[] ResponseCode = {"220","250","251","354","221"};
System.String
StrTemp = "" ;
StrTemp =
System.String.Concat("HELO ",_Identity);
StrTemp =
System.String.Concat(StrTemp,"\r\n");
SendBuffer[0] =
StrTemp ;
StrTemp = "" ;
StrTemp =
System.String.Concat("MAIL FROM: ",_MailFrom);
StrTemp =
System.String.Concat(StrTemp,"\r\n");
SendBuffer[1] =
StrTemp ;
StrTemp = "" ;
StrTemp =
System.String.Concat("RCPT TO: ",_MailTo);
StrTemp =
System.String.Concat(StrTemp,"\r\n");
SendBuffer[2] =
StrTemp ;
StrTemp = ""
;
StrTemp =
System.String.Concat("DATA","\r\n");
SendBuffer[3] =
StrTemp ;
StrTemp = "" ;
StrTemp =
System.String.Concat("From: ",_MailFrom );
StrTemp =
System.String.Concat(StrTemp,"\r\n" );
StrTemp =
System.String.Concat(StrTemp,"To: " );
StrTemp =
System.String.Concat(StrTemp,_MailTo);
StrTemp =
System.String.Concat(StrTemp,"\r\n" );
StrTemp =
System.String.Concat(StrTemp,"Subject: " );
StrTemp =
System.String.Concat(StrTemp,_Subject);
StrTemp =
System.String.Concat(StrTemp,"\r\n" );
StrTemp =
System.String.Concat(StrTemp,_MailData);
StrTemp =
System.String.Concat(StrTemp,"\r\n.\r\n");
SendBuffer[4] = StrTemp ;
StrTemp = "" ;
StrTemp =
System.String.Concat(StrTemp,"QUIT\r\n");
SendBuffer[5]
= StrTemp ;
int i = 0 ;
/* for debugging
_errmsg = "" ;
for(i=0;i<5;i++)
{
_errmsg +=
SendBuffer[i] ;
_errmsg += "<br>"
;
}
return ;
//
end of debugging
*/
while(i <
SendBuffer.Length)
{
tcp.SendCommandToServer(SendBuffer[i]) ;
ServerResponse =
tcp.GetServerResponse() ;
for(int
j=0;j<ResponseCode.Length;j++)
{
if
(tcp.DoesStringContainSMTPCode(ServerResponse,ResponseCode[j]))
{
_ServerResponse +=
ServerResponse;
_ServerResponse +=
"<br>";
break;
}
else
{
if(j==ResponseCode.Length-1)
{
_errmsg += ServerResponse
;
_errmsg += SendBuffer[i]
;
return ;
}
}
}
i++ ;
} // end of while loop ;
}// end of try block
catch(System.Net.Sockets.SocketException se)
{
_errmsg += se.Message + " "
+ se.StackTrace;
}
catch(System.Exception e)
{
_errmsg += e.Message + " "
+ e.StackTrace;
}
} // end of SendMail method
} // end of class client
} // end of namespace Ravindra
*****************end of
Modified SMTPMail.cs*********
The program is big but quite
simple . A class SMTPClient is derived from TcpClient . Hence all
protected and public properties of TcpClient are available to
SMTPClient class.
Now go directly to SendMail
class. In this class i have added several private variables and
corresponding properties like smtpserverIP,MailFrom, MailTo etc.
These properties are set
by smtpMail.aspx program which
is given below.
Property :
Description
-------------------------------------------------------------------
Identity:
This
is identity of sender e.g. ravindra
MailFrom: Sender's email
address e.g. ravindra@hotmail.com
MailTo: Recepient's email
address
Subject:
Topic of Mail
MailData: mail contents
SMTPServerIP: IP
address of SMTP server
All these inputs are received
from smtpMail.aspx file. In SendMail() method of SMTPMail class
an instance of SMTPClient class
is created and connection to smtp server is attempted .
blnconnect flag indicates
success/failure connection. If connection fails, then an error message is
genearated and program Terminates.On successful connection(i.e. blnconnect is
true) , SMTP server's response is analysed for success code
"220".If SMTP responds with success
code "220", then tha action starts.
All SMTP commands are stored in
array SendBuffer[] . All possible sucsess codes from SMTP server are stored in
array ResponseCode[].So commandes from array SendBuffer[] are sent to smtp
server one by one and for each command response from smtp server is analysed by
comparing smtp server reply code with any of possible success codes in
ResponseCode array. If the command executes successfully then only the next
command is attempted. If any of commands is unsuccessful, then error message is
generated and program terminates immediately.
Compile this smtpmail.cs file
and put it into c:/inetpub/wwwroot/bin directory .
Web based front end is given below. SMTPMail.aspx is put
into c:\inetpub\wwwroot directory which is configured as default website in IIS.
This page can be viewed in browser by Typing url http://localhost/SMTPMAil.aspx.
The page shows some texboxes to
capture input data like SMTP server ip ,sender's email , recepient;s
email, subject, Mail Data etc. and a "Send Mail" button .
When user enters data into textboxes and clicks
on "send Mail" button , a function btnSend_Click() is called. In this function ,
an instance SMTPMail() class is created. Please remember that this SMTPMail
class() has been defined in SMTPMAIL.cs file
.in btnSend_Click() we capure
inputs from user and set various properties of smail(an instance of
SMTPMail) and call its sendmail() method.
If everythis is OK ,
then a message "Mail Has been sent successfully" is displayed at the top of the
page.
If any error occurs ., then
error message is displayeed at the top.
***************** Web based
Front end (smtpMail.aspx)*******************
<%@ Import
NameSpace="Ravindra" %>
<Script language="C#"
runat="server">
void btnSend_Click(Object
Sender,EventArgs e)
{
if(Page.IsPostBack)
{
SMTPMail smail = new
SMTPMail() ; ;
smail.MailFrom =
txtfrom.Text ;
smail.MailTo = txtto.Text
;
smail.MailData =
txtmessage.Text ;
smail.Subject =
txtSubject.Text ;
smail.SMTPServerIP =
txtSMTPServerIP.Text ;
smail.SendMail();
if (smail.ErrorMessage!="")
{
Response.Write("Error:
" + smail.ErrorMessage) ;
}
else
{
/*
for debugging only.
Response.Write(smail.ServerResponse + "Mail Sent
successfully") ;
*/
Response.Write("<br>Mail
Sent successfully<br>") ;
}
}
}
</script>
<html>
<head>
<title>SMTP E-Mail Example
by Ravindra Sadaphule
</title>
</head>
<body>
<form name="frm1"
runat="server">
<table width="100%">
<tr>
<td colspan="2"
align="center"><h3>SMTP MAIL </h3></td>
</tr>
<tr>
<td width="30%"
align="center" valign="middle" >SMTP SERVER
IP:</td>
<td width="70%"
align="left" valign="middle" >
<asp:textbox
id="txtSMTPServerIP" runat="server" />e.g.
127.0.0.1
</td>
</tr>
<tr>
<td width="30%"
align="center" valign="middle" >
From:
</td>
<td width="70%"
align="left" valign="middle" >
<asp:textbox id="txtfrom"
runat="server" />e.g. ravi_sadaphule@hotmail.com
</td>
</tr>
<tr>
<td width="30%"
align="center" valign="middle" >
To:
</td>
<td width="70%"
align="left" valign="middle" >
<asp:textbox id="txtto"
runat="server" />e.g. tarunt@bharat.com
</td>
</tr>
<tr>
<td width="30%"
align="center" valign="middle" >
Sub:
</td>
<td width="50%"
align="left" valign="middle" >
<asp:textbox
id="txtSubject" runat="server" />e.g. Marriage
Proposal
</td>
</tr>
<tr>
<td width=
"30%"align="center"valign="middle" >
Message:
</td>
<td width="70%"
align="left" valign="middle" >
<asp:textbox
id="txtmessage" TextMode="MultiLine" Rows="5"
runat="server" />
</td>
</tr>
<tr>
<td width="30%"
align="center" valign="middle" > </td>
<td width="70%"
align="left" valign="middle" >
<asp:button text="Send
Mail" id="btnSend" OnClick="btnSend_Click"
runat="server" />
</td>
</tr>
<tr>
<td width="30%"
align="center" valign="middle" > </td>
<td width="70%"
align="left" valign="middle">Developer:
<a
href="mailto:ravi_sadaphule@hotmail.com"> Ravindra
Sadaphule</a>
</td>
</tr>
</table>
</form>
</body>
</html>
*******************end of web
based front end ************