Created
July 29, 2012 00:42
-
-
Save mikeobrien/3195464 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MemorySmtpServer | |
{ | |
private readonly bool _redirectSmtpConfiguration; | |
private const int Port = 62352; | |
private readonly Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); | |
private MailSettingsSectionGroup _mailSettings; | |
private string _originalHost; | |
private int _originalPort; | |
private SmtpServer _server; | |
public MemorySmtpServer(bool redirectSmtpConfiguration) | |
{ | |
_redirectSmtpConfiguration = redirectSmtpConfiguration; | |
} | |
public MemoryMessageSpool Messages { get; private set; } | |
public void Start() | |
{ | |
if (_redirectSmtpConfiguration) | |
{ | |
_mailSettings = _configuration.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; | |
_originalHost = _mailSettings.Smtp.Network.Host; | |
_originalPort = _mailSettings.Smtp.Network.Port; | |
_mailSettings.Smtp.Network.Host = "127.0.0.1"; | |
_mailSettings.Smtp.Network.Port = Port; | |
_configuration.Save(); | |
} | |
Messages = new MemoryMessageSpool(); | |
_server = new SmtpServer(port: Port, messageSpool: Messages, recipientFilter: (context, address) => true); | |
_server.Start(); | |
} | |
public void Stop() | |
{ | |
_server.Stop(); | |
if (_redirectSmtpConfiguration) | |
{ | |
_mailSettings.Smtp.Network.Host = _originalHost; | |
_mailSettings.Smtp.Network.Port = _originalPort; | |
_configuration.Save(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment