Click here to Skip to main content
15,881,812 members
Articles / Programming Languages / C#
Tip/Trick

Create a simple SMTP server in C#

Rate me:
Please Sign up or sign in to vote.
4.88/5 (12 votes)
20 Nov 2011CPOL 186.9K   29   17
A simple basic SMTP server for testing purposes
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)


Written By
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionwhat about the mail queue? Pin
Pal Sayantan14-Mar-18 23:47
Pal Sayantan14-Mar-18 23:47 
GeneralMy vote of 1 Pin
Jason McBurney5-Mar-18 6:02
Jason McBurney5-Mar-18 6:02 
NewsSure would be handy to know... Pin
countrysideflair23-May-13 14:15
countrysideflair23-May-13 14:15 
GeneralMy vote of 2 Pin
perilbrain16-Feb-13 1:57
perilbrain16-Feb-13 1:57 
GeneralRe: My vote of 2 Pin
Jason McBurney5-Mar-18 6:01
Jason McBurney5-Mar-18 6:01 
Suggestionthanks i am now going to design smtpserver.in powered relay Pin
smtpserver.in7-Nov-12 20:47
smtpserver.in7-Nov-12 20:47 
Questionplease some one help me how to test dkim with smtpserver relay Pin
smtpserver.in22-Oct-12 4:12
smtpserver.in22-Oct-12 4:12 
Questionsmtp server in c Pin
Igede Hardisurya Budiana7-Oct-12 15:19
Igede Hardisurya Budiana7-Oct-12 15:19 
QuestionOne more update to my alternate version - full source Pin
Al Forno11-Sep-12 10:15
Al Forno11-Sep-12 10:15 
AnswerRe: One more update to my alternate version - full source Pin
ObiWan_MCC17-Sep-12 3:42
ObiWan_MCC17-Sep-12 3:42 
QuestionAnother alternate - full source Pin
Al Forno11-Sep-12 8:07
Al Forno11-Sep-12 8:07 
GeneralRe: Another alternate - full source Pin
partha chakraborti14-Jan-15 19:46
partha chakraborti14-Jan-15 19:46 
AnswerRe: Another alternate - full source Pin
Member 1185245119-Jul-16 6:05
Member 1185245119-Jul-16 6:05 
SuggestionSome suggestion to improve your tip Pin
ObiWan_MCC3-Sep-12 6:13
ObiWan_MCC3-Sep-12 6:13 
First of all, I think that you left out too much stuff from your example and this, in turn, makes it difficult to understand; it would have been a better idea adding some "full" code like the one shown here[^]; then, it would be useful to add some code to the "Run()" method to set the client socket "ReceiveTimeout" property (see here[^]) to a value different from "infinite" (aka zero); for example 5000, this way, a client connecting to the server and idling withouth sending in any command for some time (five seconds in my example) would be automatically disconnected.

just to be clear, here's the modified code snippet from the first URL above

C#
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace FakeSMTP
{
    public class SMTPServer
    {
        TcpClient client;
        NetworkStream stream;
        System.IO.StreamReader reader;
        System.IO.StreamWriter writer;
        
        public SMTPServer(TcpClient client)
        {
            this.client = client;
            this.client.ReceiveTimeout = 5000;
            stream = client.GetStream();
            reader = new System.IO.StreamReader(stream);
            writer = new System.IO.StreamWriter(stream);
            writer.NewLine = "\r\n";
            writer.AutoFlush = true;
        }

        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Loopback,25);
            listener.Start();
            while (true)
            {
                SMTPServer handler = new SMTPServer(listener.AcceptTcpClient());
                Thread thread = new System.Threading.Thread(new ThreadStart(handler.Run));
                thread.Start();
            }
        }
        
        public void Run()
        {
            writer.WriteLine("220 localhost -- Fake proxy server");
            for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
            {
                Console.Error.WriteLine("Read line {0}", line);
                switch (line)
                {
                    case "DATA":
                        writer.WriteLine("354 Start input, end data with <CRLF>.<CRLF>");
                        StringBuilder data = new StringBuilder();
                        String subject = "";
                        line = reader.ReadLine();
                        if (line != null && line != ".")
                        {
                            const string SUBJECT = "Subject: ";
                            if (line.StartsWith(SUBJECT))
                                subject = line.Substring(SUBJECT.Length);
                            else data.AppendLine(line);
                            for (line = reader.ReadLine();
                                line != null && line != ".";
                                line = reader.ReadLine())
                            {
                                data.AppendLine(line);
                            }
                        }
                        String message = data.ToString();
                        Console.Error.WriteLine("Received ­ email with subject: {0} and message: {1}",
                            subject, message);
                        writer.WriteLine("250 OK");
                        client.Close();
                        return;
                    default:
                        writer.WriteLine("250 OK");
                        break;
                }
            }
        }
    }
}


I admit that the above code is simpler and probably less elegant than yours, but at least it helps understanding how the whole thing works and, the timeout setting avoids ending up with a bunch of sockets idling and doing nothing Smile | :)

HTH
GeneralReason for my vote of 5 Thanks man! It works but my firewall... Pin
finkos24-Nov-11 8:31
finkos24-Nov-11 8:31 
GeneralYou did not define the server variable in your code. What is... Pin
finkos22-Nov-11 14:51
finkos22-Nov-11 14:51 
GeneralReason for my vote of 5 good - i'll give it a try! Pin
johannesnestler22-Nov-11 7:13
johannesnestler22-Nov-11 7:13 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.