public void HandleRequest() { Email email = null; var lstRcptTo = new List <string>(); using (var stream = _client.GetStream()) { using (var writer = new StreamWriter(stream)) { writer.NewLine = "\r\n"; writer.AutoFlush = true; using (var reader = new StreamReader(stream)) { writer.WriteLine("220 localhost -- Fake proxy server"); try { var keepReading = true; while (keepReading) { var line = ReadNextLine(reader); /* Each email address shows up one per line with "RCPT TO:" as a prefix * It's a mix of To, Cc and Bcc. Bcc doesn't have a dedicated prefix * so this is how I am dealing with it for now. */ CollectRcptTo(lstRcptTo, line); switch (line) { case "DATA": writer.WriteLine("354 Start input, end data with <CRLF>.<CRLF>"); var parser = EmailParser.GetEmailParser(reader, lstRcptTo, _verboseOutput); if (parser == null) { throw new Exception( "Parser was returned as null somehow... 0x202002020103"); } parser.ParseBody(); email = parser.GetEmail(); var attachments = parser.GetAttachments(); email.AttachmentCount = attachments.Count; if (attachments.Any()) { var svc = new AttachmentCompressor(attachments); var rawFile = svc.SaveAsZipArchive(Path.GetRandomFileName()); email.AttachmentArchive = rawFile.Contents; } WriteMessage(email); var svcEmail = new EmailService(email); svcEmail.ValidateEmail(); svcEmail.SaveEmail(); writer.WriteLine("250 OK"); break; case "QUIT": writer.WriteLine("250 OK"); keepReading = false; break; default: writer.WriteLine("250 OK"); break; } } } catch (InvalidEmailException iee) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("This email cannot not be saved. Check log for more details."); Console.ResetColor(); _log.LogError(iee, email); } catch (IOException ioe) { Console.BackgroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine("Connection lost."); Console.ResetColor(); _log.LogError(ioe, email); } catch (Exception ex) { _log.LogError(ex, email); } } } } }