2 // SmtpServer.cs - Dummy SMTP server used to test SmtpClient
5 // Raja R Harinath <harinath@hurrynot.org>
9 using System.Diagnostics;
12 using System.Net.Mail;
13 using System.Net.Sockets;
15 using System.Threading;
17 namespace MonoTests.System.Net.Mail {
18 public class SmtpServer
20 public string mail_from, rcpt_to;
21 public StringBuilder data;
24 public IPEndPoint EndPoint {
25 get { return (IPEndPoint) server.LocalEndpoint; }
30 server = new TcpListener (0);
34 private static void WriteNS (NetworkStream ns, string s)
36 Trace ("response", s);
37 byte [] bytes = Encoding.ASCII.GetBytes (s);
38 ns.Write (bytes, 0, bytes.Length);
44 using (TcpClient client = server.AcceptTcpClient ()) {
45 Trace ("connection", EndPoint.Port);
46 using (NetworkStream ns = client.GetStream ()) {
47 WriteNS (ns, "220 localhost\r\n");
48 using (StreamReader r = new StreamReader (ns, Encoding.UTF8)) {
49 while ((s = r.ReadLine ()) != null && Dispatch (ns, r, s))
56 // return false == terminate
57 public bool Dispatch (NetworkStream ns, StreamReader r, string s)
61 WriteNS (ns, "502 Huh\r\n");
66 switch (s.Substring (0, 4)) {
70 WriteNS (ns, "221 Quit\r\n");
73 mail_from = s.Substring (10);
76 rcpt_to = s.Substring (8);
79 WriteNS (ns, "354 Continue\r\n");
80 data = new StringBuilder ();
81 while ((s = r.ReadLine ()) != null) {
86 Trace ("end of data", s);
90 WriteNS (ns, "502 Huh\r\n");
94 WriteNS (ns, "250 OK\r\n");
98 [Conditional ("TEST")]
99 static void Trace (string key, object value)
101 Console.Error.WriteLine ("{0}: {1}", key, value);
105 static void DoTest (SmtpServer s, SmtpClient c, MailMessage m)
107 Thread t = new Thread (s.Run);
112 Console.WriteLine ("Message From: {0}", m.From);
113 Console.WriteLine ("Message Sender: {0}", m.Sender);
114 Console.WriteLine ("Mail From: {0}", s.mail_from);
115 Console.WriteLine ("Rcpt To: {0}", s.rcpt_to);
116 Console.WriteLine ("-------------------------------------");
117 Console.Write (s.data);
118 Console.WriteLine ("-------------------------------------");
123 var server = new SmtpServer ();
124 var client = new SmtpClient ("localhost", server.EndPoint.Port);
125 var msg = new MailMessage ("foo@example.com", "bar@example.com", "hello", "howdydoo");
127 DoTest (server, client, msg);
129 msg.Sender = new MailAddress ("baz@example.com");
131 DoTest (server, client, msg);