Click here to Skip to main content
Click here to Skip to main content

Create a simple SMTP server in C#

By , 20 Nov 2011
 
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);//Handles all messages in the protocol
 smtp.Dispose();//sends a Quit message
 
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)
        {
            //a socket error has occured
            break;
        }
 
        if (strMessage.Length > 0)
        {
            if (strMessage.StartsWith("QUIT"))
            {
                client.Close();
                break;//exit while
            }
            //message has successfully been received
            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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

roosrj
Netherlands Netherlands
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
NewsSure would be handy to know...membercountrysideflair23 May '13 - 14:15 
GeneralMy vote of 2memberperilbrain16 Feb '13 - 1:57 
Suggestionthanks i am now going to design smtpserver.in powered relaymembersmtpserver.in7 Nov '12 - 20:47 
Questionplease some one help me how to test dkim with smtpserver relaymembersmtpserver.in22 Oct '12 - 4:12 
Questionsmtp server in cmemberIgede Hardisurya Budiana7 Oct '12 - 15:19 
QuestionOne more update to my alternate version - full sourcememberMark Harmon11 Sep '12 - 10:15 
AnswerRe: One more update to my alternate version - full sourcememberObiWan_MCC17 Sep '12 - 3:42 
QuestionAnother alternate - full sourcememberMark Harmon11 Sep '12 - 8:07 
SuggestionSome suggestion to improve your tipmemberObiWan_MVP3 Sep '12 - 6:13 
GeneralReason for my vote of 5 Thanks man! It works but my firewall...memberfinkos24 Nov '11 - 8:31 
Reason for my vote of 5
Thanks man! It works but my firewall is barking at IPAddress.Any.
So I replaced it with
 
IPAddress address = null;
if (IPAddress.TryParse("127.0.0.1", out address))
{
//IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 25);
IPEndPoint endPoint = new IPEndPoint(address, 25);
listener = new TcpListener(endPoint);
}
GeneralYou did not define the server variable in your code. What is...memberfinkos22 Nov '11 - 14:51 
GeneralReason for my vote of 5 good - i'll give it a try!memberjohannesnestler22 Nov '11 - 7:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 21 Nov 2011
Article Copyright 2011 by roosrj
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid