.net smtp listener

Is there a way for using .net to create a console app. or service to listen for SMTP messages over a certain port?

I need to create a middle tier object that will capture and process smtp messages. That is to say i want smtp messages sent and picked up by this listener and then broken down to its basic components and persisted to a sql server DB.

If there is a off the shelf solution even better. I was not able to find one as I scurried the web.

Note: smtp sender will be a web app on the network, as well as exchange. The listener will be assigned some port so all smpt traffic on this port will be designated for my particular application.
realcodingAsked:
Who is Participating?
 
käµfm³d 👽Connect With a Mentor Commented:
So I put this together out of sheer curiosity, although I do agree with tgerbert that you may find an ready-built solution more easy to apply. My hope is that if you wanted to do the code yourself, then this will give you a start. This example is *extremely* basic. There is only one iteration on the "server;" in reality, I would expect this to be in a loop waiting for new connections. There is no serious error checking, and I may not be following the SMTP protocol strictly (I did intend to). There is no verification of the recipient as I'm not sure how you'd want to verify that.

Server
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApplication42
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Loopback, 8000);
            TcpClient client;
            NetworkStream ns;
            
            listener.Start();

            Console.WriteLine("Awaiting connection...");
            client = listener.AcceptTcpClient();
            Console.WriteLine("Connection accepted!");

            ns = client.GetStream();

            using (StreamWriter writer = new StreamWriter(ns))
            {
                writer.WriteLine("220 localhost SMTP server ready.");
                writer.Flush();

                using (StreamReader reader = new StreamReader(ns))
                {
                    string response = reader.ReadLine();

                    if (!response.StartsWith("HELO") && !response.StartsWith("EHLO"))
                    {
                        writer.WriteLine("500 UNKNOWN COMMAND");
                        writer.Flush();
                        ns.Close();
                        return;
                    }

                    string remote = response.Replace("HELO", string.Empty).Replace("EHLO", string.Empty).Trim();

                    writer.WriteLine("250 localhost Hello " + remote);
                    writer.Flush();

                    response = reader.ReadLine();

                    if (!response.StartsWith("MAIL FROM:"))
                    {
                        writer.WriteLine("500 UNKNOWN COMMAND");
                        writer.Flush();
                        ns.Close();
                        return;
                    }

                    remote = response.Replace("RCPT TO:", string.Empty).Trim();
                    writer.WriteLine("250 " + remote + " I like that guy too!");
                    writer.Flush();

                    response = reader.ReadLine();

                    if (!response.StartsWith("RCPT TO:"))
                    {
                        writer.WriteLine("500 UNKNOWN COMMAND");
                        writer.Flush();
                        ns.Close();
                        return;
                    }

                    remote = response.Replace("MAIL FROM:", string.Empty).Trim();
                    writer.WriteLine("250 " + remote + " I like that guy!");
                    writer.Flush();

                    response = reader.ReadLine();

                    if (response.Trim() != "DATA")
                    {
                        writer.WriteLine("500 UNKNOWN COMMAND");
                        writer.Flush();
                        ns.Close();
                        return;
                    }

                    writer.WriteLine("354 Enter message. When finished, enter \".\" on a line by itself");
                    writer.Flush();

                    int counter = 0;
                    StringBuilder message = new StringBuilder();

                    while ((response = reader.ReadLine().Trim()) != ".")
                    {
                        message.AppendLine(response);
                        counter++;

                        if (counter == 1000000)
                        {
                            ns.Close();
                            return;  // Seriously? 1 million lines in a message?
                        }
                    }

                    writer.WriteLine("250 OK");
                    writer.Flush();
                    ns.Close();
                    // Insert "message" into DB
                    Console.WriteLine("Received message:");
                    Console.WriteLine(message.ToString());
                }
            }

            Console.ReadKey();
        }
    }
}

Open in new window



Client
using System.Net;
using System.Net.Mail;

namespace ConsoleApplication43
{
    class Program
    {
        static void Main(string[] args)
        {
            MailMessage message = new MailMessage("ma@example.com", "pa@example.com");
            SmtpClient client = new SmtpClient(IPAddress.Loopback.ToString(), 8000);

            message.Body = "Don't forget to pick up some milk from the market.";

            client.Send(message);
        }
    }
}

Open in new window


Here are the references I used in creating the example above:

    https://helpdesk.islandnet.com/pep/smtp.php
    http://www.networksorcery.com/enp/protocol/smtp.htm




untitled.PNG
0
 
käµfm³d 👽Commented:
Have you looked into the System.Net.Sockets.TcpListener class?
0
 
realcodingAuthor Commented:
kaufmed:

i have not worked with this class yet. can you explain how this would help me?
0
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

 
Todd GerbertConnect With a Mentor IT ConsultantCommented:
I doubt you'll want to code a complete SMTP server from scratch.  This forum discussion lists a couple options for off-the-shelf components: http://stackoverflow.com/questions/249047/smtp-and-imap-server-library-for-net
0
 
käµfm³d 👽Commented:
P.S.

I arbitrarily used 8000 because our virus scanner at work is set up to block 25 by default. You can change it accordingly  : )
0
 
Todd GerbertIT ConsultantCommented:
Here's the actual standard from the IETF, note section 4.5.1 lists the minimum required to comply with the standard.  You would probably need to meet those minimums to effectively work with commercial SMTP servers like Exchange.  There are also other details you need to be aware of (like maximum length for a "MAIL FROM:<>" command, and encoding of periods in message data).

http://tools.ietf.org/html/rfc821
0
 
käµfm³d 👽Commented:
@tgerbert

I started off looking at that, but after a few minutes I said, "Man, that's a lot to read!"

; )
0
 
Todd GerbertIT ConsultantCommented:
Yeah, but most of it's not necessarily applicable - the list of minimum required commands is pretty short.
0
 
realcodingAuthor Commented:
thanks all, i have got some serious reading to do. also ill try your POC app as well. thanks all for the great help !
0
 
käµfm³d 👽Commented:
NP. Glad to help  = )
0
 
realcodingAuthor Commented:
@kaufmed,

I have the consul apps made but my environment is preventing mail from going out and telling me the server actively refused the connection. do i need to config something aside from running the apps?
0
 
käµfm³d 👽Commented:
>>  server actively refused the connection.

That usually means the server doesn't have that port open (i.e. the service isn't running). There could also be firewall or antivirus restrictions, I imagine. Can you confirm none of these is the case?
0
All Courses

From novice to tech pro — start learning today.