I created for testing purposes a simple SMTP server.
This is the client call:
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("localhost");
smtp.Send(message);
smtp.Dispose();
This is the basic server code:
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 25);
TcpListener listener = new TcpListener(endPoint);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
SMTPServer handler = new SMTPServer();
servers.Add(handler);
handler.Init(client);
Thread thread = new System.Threading.Thread(new ThreadStart(handler.Run));
thread.Start();
}
The protocol has the following messages in this example:
C : EHLO
S: 250 Ok
C : MAIL FROM
S: 250 OK
C : RCPT TO
S: 250 OK
C :DATA
S: 354 Start mail input; end with <crlf>.<crlf>
DATA....
S: 250 OK
C : Quit
</crlf></crlf>
Basically the Run method contains this:
public void Run()
{
Write("220 localhost -- Fake proxy server");
string strMessage = String.Empty;
while (true)
{
try
{
strMessage = Read();
}
catch(Exception e)
{
break;
}
if (strMessage.Length > 0)
{
if (strMessage.StartsWith("QUIT"))
{
client.Close();
break;
}
if (strMessage.StartsWith("EHLO"))
{
Write("250 OK");
}
if (strMessage.StartsWith("RCPT TO"))
{
Write("250 OK");
}
if (strMessage.StartsWith("MAIL FROM"))
{
Write("250 OK");
}
if (strMessage.StartsWith("DATA"))
{
Write("354 Start mail input; end with");
strMessage = Read();
Write("250 OK");
}
}
}
}
private void Write(String strMessage)
{
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(strMessage + "\r\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
private String Read()
{
byte[] messageBytes = new byte[8192];
int bytesRead = 0;
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
bytesRead = clientStream.Read(messageBytes, 0, 8192);
string strMessage = encoder.GetString(messageBytes, 0, bytesRead);
return strMessage;
}
Happy coding!