public async void Start() { _cancellationTokenSource = new CancellationTokenSource(); var telegramSettings = TelegramConfiguration.Read(); var telegramAsMessageStore = new TelegramAsMessageStore(telegramSettings.Token, telegramSettings.ChatId); var smtpSettings = SmtpConfiguration.Read(); var options = new SmtpServerOptionsBuilder() .Port(smtpSettings.Port) .Build(); var serviceProvider = new ServiceProvider(); serviceProvider.Add(telegramAsMessageStore); var smtpServer = new SmtpServer.SmtpServer(options, serviceProvider); _ = new SmtpSessionLogger(smtpServer, _log); await smtpServer.StartAsync(_cancellationTokenSource.Token); if (Environment.UserInteractive) { _log.Warn($"{ServiceName} started in interactive mode"); } else { _log.Warn($"{ServiceName} service started"); } }
/// <summary> /// Create a running instance of a server. /// </summary> /// <param name="configuration">The configuration to apply to run the server.</param> /// <param name="beforeStart">Action invoked before the server is started.</param> /// <returns>A disposable instance which will close and release the server instance.</returns> private SmtpServerDisposable CreateServer(Action <SmtpServerOptionsBuilder> configuration, Action <SmtpServer> beforeStart) { var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(9025) .MessageStore(MessageStore); configuration(options); var server = new SmtpServer(options.Build()); beforeStart(server); var smtpServerTask = server.StartAsync(CancellationTokenSource.Token); return(new SmtpServerDisposable(server, () => { CancellationTokenSource.Cancel(); try { smtpServerTask.Wait(TestWaitTimeout); } catch (AggregateException e) { e.Handle(exception => exception is OperationCanceledException); } })); }
static async Task Main(string[] args) { //CustomEndpointListenerExample.Run(); ServicePointManager.ServerCertificateValidationCallback = SmtpServerTests.IgnoreCertificateValidationFailureForTestingOnly; //var options = new SmtpServerOptionsBuilder() // .ServerName("SmtpServer SampleApp") // .Port(587, false) // //.Certificate(SmtpServerTests.CreateCertificate()) // .Build(); var options = new SmtpServerOptionsBuilder() .ServerName("SmtpServer SampleApp") .Endpoint(endpoint => endpoint .Port(587) .AllowUnsecureAuthentication(true) .AuthenticationRequired(false)) .UserAuthenticator(new SampleUserAuthenticator()) //.Certificate(SmtpServerTests.CreateCertificate()) .Build(); var server = new SmtpServer.SmtpServer(options); server.SessionCreated += OnSessionCreated; server.SessionCompleted += OnSessionCompleted; server.SessionFaulted += OnSessionFaulted; var serverTask = server.StartAsync(CancellationToken.None); Console.ReadKey(); await serverTask.ConfigureAwait(false); }
private async void Start_Click(object sender, EventArgs e) { EnableDisable(false); TimeSpan seconds = TimeSpan.FromSeconds(Decimal.ToDouble(timeout.Value)); LoggingMessageStore store = new LoggingMessageStore(); store.Message += Store_Message; ISmtpServerOptions options = new SmtpServerOptionsBuilder() .ServerName(serverName.Text) .Port(Decimal.ToInt32(port.Value)) .CommandWaitTimeout(seconds) .MessageStore(store) .Build(); smtpServer = new SmtpServer.SmtpServer(options); smtpServer.SessionCreated += OnSessionCreated; try { cancellationTokenSource = new CancellationTokenSource(); await smtpServer.StartAsync(cancellationTokenSource.Token) .ConfigureAwait(true); } catch (SocketException ex) { MessageBox.Show(this, ex.Message, this.Text); } catch (OperationCanceledException) { // nothing for user to do } EnableDisable(true); }
public static void Run() { _cancellationTokenSource = new CancellationTokenSource(); var options = new SmtpServerOptionsBuilder() .ServerName("SmtpServer SampleApp") .Endpoint(builder => builder .AllowUnsecureAuthentication() .AuthenticationRequired() .Port(9025)) .Build(); var serviceProvider = new ServiceProvider(); serviceProvider.Add(new AuthenticationHandler()); var server = new SmtpServer.SmtpServer(options, serviceProvider); server.SessionCreated += OnSessionCreated; server.SessionCompleted += OnSessionCompleted; var serverTask = server.StartAsync(_cancellationTokenSource.Token); SampleMailClient.Send(user: "******", password: "******", count: 5); serverTask.WaitWithoutException(); }
internal static IServiceCollection AddSmtpRouter(this IServiceCollection services) { return(services.AddTransient(sp => { var userAuthenticator = new DelegatingUserAuthenticator((s, u, p) => { /* * Do authentication here or write your own IUserAuthenticatorFactory. * We add the username to the SessionContext. It is used by in the Reroute middleware example. */ s.Properties["SmtpUsername"] = u; return true; }); var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .UserAuthenticator(userAuthenticator) .Endpoint(b => { b.Port(25, false); b.AuthenticationRequired(false); b.AllowUnsecureAuthentication(true); }) .MessageStore(sp.GetRequiredService <IMessageStoreFactory>()) .Logger(sp.GetRequiredService <SmtpLoggerWrapper>()) .Build(); return new SmtpServer.SmtpServer(options); })); }
public void Start(EndpointDefinition smtpEndpoint) { ServicePointManager.ServerCertificateValidationCallback = IgnoreCertificateValidationFailureForTestingOnly; _currentEndpoint = smtpEndpoint; var options = new SmtpServerOptionsBuilder() .ServerName(_applicationMetaData.AppName) .UserAuthenticator(new SimpleAuthentication()) .MailboxFilter(new DelegatingMailboxFilter(CanAcceptMailbox)) .Logger(_bridgeLogger) .MessageStore(_messageStore); options = options.Endpoint(new EndpointDefinitionBuilder() .Endpoint(smtpEndpoint.ToIPEndPoint()) .IsSecure(false) .AllowUnsecureAuthentication(false) .Build()); var server = new SmtpServer(options.Build()); server.SessionCreated += OnSessionCreated; server.SessionCompleted += OnSessionCompleted; _logger.Information("Starting Smtp Server on {IP}:{Port}...", ListenIpAddress, ListenPort); _tokenSource = new CancellationTokenSource(); _smtpServerTask = server.StartAsync(_tokenSource.Token); }
public void Run() { var cancellationTokenSource = new CancellationTokenSource(); var options = new SmtpServerOptionsBuilder() .ServerName("mail-x.domain.com") .Endpoint(b => b .Port(8025) .AuthenticationRequired() .AllowUnsecureAuthentication() ) .CommandWaitTimeout(TimeSpan.FromSeconds(100)) .EndpointAuthenticator(new SimpleEndpointAuthenticator()) .ProxyAddresses(new List <string>() { "192.168.1.1" }) .Build(); var server = new SmtpServer(options); server.SessionCreated += OnSessionCreated; server.SessionCompleted += OnSessionCompleted; var serverTask = server.StartAsync(cancellationTokenSource.Token); Console.WriteLine("Press any key to shutdown"); Console.ReadKey(); cancellationTokenSource.Cancel(); serverTask.Wait(); }
public static void Run() { var cancellationTokenSource = new CancellationTokenSource(); var options = new SmtpServerOptionsBuilder() .ServerName("SmtpServer SampleApp") .Port(9025) .MailboxFilter(new SampleMailboxFilter(TimeSpan.FromSeconds(5))) .Build(); var server = new SmtpServer.SmtpServer(options); server.SessionCreated += OnSessionCreated; server.SessionCompleted += OnSessionCompleted; server.SessionFaulted += OnSessionFaulted; server.SessionCancelled += OnSessionCancelled; var serverTask = server.StartAsync(cancellationTokenSource.Token); // ReSharper disable once MethodSupportsCancellation Task.Run(() => SampleMailClient.Send()); Console.WriteLine("Press any key to cancel the server."); Console.ReadKey(); Console.WriteLine("Forcibily cancelling the server and any active sessions"); cancellationTokenSource.Cancel(); serverTask.WaitWithoutException(); Console.WriteLine("The server has been cancelled."); }
public static void Run() { var cancellationTokenSource = new CancellationTokenSource(); var options = new SmtpServerOptionsBuilder() .ServerName("SmtpServer SampleApp") .Certificate(CreateCertificate()) .Endpoint(builder => builder .Port(9025, true) .AllowUnsecureAuthentication(false)) .Build(); var serviceProvider = new ServiceProvider(); serviceProvider.Add(new CustomEndpointListenerFactory()); var server = new SmtpServer.SmtpServer(options, serviceProvider); var serverTask = server.StartAsync(cancellationTokenSource.Token); SampleMailClient.Send(useSsl: true); cancellationTokenSource.Cancel(); serverTask.WaitWithoutException(); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); IConfiguration config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", true, true) .AddEnvironmentVariables() .Build(); var port = int.Parse(config.GetSection("Port").Value); var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(port) .MessageStore(new LupusMessageStore(config, _logger)) .Build(); _logger.LogInformation($"Starting SMTP server on port {port}"); var smtpServer = new SmtpServer.SmtpServer(options); await smtpServer.StartAsync(stoppingToken); } }
/// <summary> /// Create a running instance of a server. /// </summary> /// <param name="serverConfiguration">The configuration to apply to run the server.</param> /// <param name="endpointConfiguration">The configuration to apply to the endpoint.</param> /// <returns>A disposable instance which will close and release the server instance.</returns> SmtpServerDisposable CreateServer( Action <SmtpServerOptionsBuilder> serverConfiguration, Action <EndpointDefinitionBuilder> endpointConfiguration) { var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Endpoint( endpointBuilder => { endpointBuilder.Port(9025); endpointConfiguration(endpointBuilder); }) .MessageStore(MessageStore); serverConfiguration(options); var server = new SmtpServer(options.Build()); var smtpServerTask = server.StartAsync(CancellationTokenSource.Token); return(new SmtpServerDisposable(server, () => { CancellationTokenSource.Cancel(); try { smtpServerTask.Wait(); } catch (AggregateException e) { e.Handle(exception => exception is OperationCanceledException); } })); }
public static void Run() { // this is important when dealing with a certificate that isnt valid ServicePointManager.ServerCertificateValidationCallback = IgnoreCertificateValidationFailureForTestingOnly; var cancellationTokenSource = new CancellationTokenSource(); var options = new SmtpServerOptionsBuilder() .ServerName("SmtpServer SampleApp") .Certificate(CreateCertificate()) .AllowUnsecureAuthentication(false) .UserAuthenticator(new SampleUserAuthenticator()) .Port(9025, true) .Build(); var server = new SmtpServer.SmtpServer(options); server.SessionCreated += OnSessionCreated; var serverTask = server.StartAsync(cancellationTokenSource.Token); SampleMailClient.Send(user: "******", password: "******", useSsl: true); cancellationTokenSource.Cancel(); serverTask.WaitWithoutException(); }
static SmtpParser CreateParser(string text) { var segment = new ArraySegment <byte>(Encoding.UTF8.GetBytes(text)); var options = new SmtpServerOptionsBuilder().Logger(new NullLogger()).Build(); return(new SmtpParser(options, new TokenEnumerator(new ByteArrayTokenReader(new [] { segment })))); }
public async Task StartAsync(CancellationToken cancellationToken) { var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(25, 587) .MessageStore(new RadishMessageStore(queueService)) .Build(); server = new SmtpServer.SmtpServer(options); await server.StartAsync(cancellationToken); }
private async Task StartSmtpServer(string host, int port) { var options = new SmtpServerOptionsBuilder() .ServerName(host) .Port(port) .MessageStore(new SmtpForMeMessageStore()) .Build(); var smtpServer = new SmtpServer.SmtpServer(options); await smtpServer.StartAsync(CancellationToken.None); }
private void StartEmailServer() { var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(smtpPort) .MessageStore(new SampleMessageStore()) .Build(); var smtpServer = new SmtpServer.SmtpServer(options); smtpServer.StartAsync(CancellationToken.None); }
public async void StartServer() { var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(25, 587) .MessageStore(new MS()) .MailboxFilter(new MF()) .UserAuthenticator(new UA()) .Build(); var smtpServer = new SmtpServer.SmtpServer(options); await smtpServer.StartAsync(CancellationToken.None); }
public async Task <bool> Run(CancellationToken token, Logger log) { var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(25, 587) .MessageStore(new MessageStore()) .Build(); var smtpServer = new SmtpServer.SmtpServer(options); await smtpServer.StartAsync(token); return(true); }
public MailServer(int?numMessages = null, int?memoryLimit = null) { var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(25, 587) .Port(465, isSecure: true) //.Certificate(CreateX509Certificate2()) .MessageStore(new InMemoryMessageStore(numMessages, memoryLimit)) .MailboxFilter(new CustomMailboxFilter()) .UserAuthenticator(new CustomUserAuthenticator()) .Build(); _options = options; }
/// <summary> /// Initializes a new instance of the Listener /// </summary> /// <param name="cancellationToken">The Cancellation Token to stop a transaction</param> /// <returns>An awaitable <see cref="Task"/> with the listener to Smtp Messages</returns> public async Task StartAsync(CancellationToken cancellationToken) { // Parameters for the SMTP Server ISmtpServerOptions options; // Setup the MessageStore SmtpMessageStore smtpMessageStore = new SmtpMessageStore(); smtpMessageStore.MessageReceived += SmtpMessageStore_MessageReceived; smtpMessageStore.MessageReceivedWithErrors += SmtpMessageStore_MessageReceivedWithErrors; // Configure the SMTP Server Parameters if (this.RequiresAuthentication) { // Setup the UserAuthenticator SmtpAuthenticator smtpAuthenticator = new SmtpAuthenticator(); options = new SmtpServerOptionsBuilder().ServerName(this.ServerName) .Port(this.Ports) .AllowUnsecureAuthentication(!this.UseSSL) .AuthenticationRequired(true) .MessageStore(smtpMessageStore) .UserAuthenticator(smtpAuthenticator) .Build(); } else { options = new SmtpServerOptionsBuilder().ServerName(this.ServerName) .Port(this.Ports) .AllowUnsecureAuthentication(!this.UseSSL) .AuthenticationRequired(false) .MessageStore(smtpMessageStore) .Build(); } // Initialize the SMTP Server Server = new SmtpServer.SmtpServer(options); // Hook the events Server.SessionCreated += Server_OnSessionCreated; Server.SessionCompleted += Server_OnSessionCompleted; // Sets the Listening to on and kick event IsListening = true; ListeningStarted?.Invoke(this, null); // Starts the SMTP Server await Server.StartAsync(cancellationToken); }
public void ConfigureServices(IServiceCollection services) { services.AddRouting(options => { options.AppendTrailingSlash = true; options.LowercaseUrls = true; }); services.AddControllersWithViews(); services.AddSignalR(); services.AddLogging(options => { options.AddConfiguration(Configuration.GetSection("Logging")); options.AddConsole(); if (!HostingEnvironment.IsDevelopment()) { options.AddProvider(new SlackLoggerProvider(Configuration["Slack:Token"])); } options.Services.AddSingleton <ILoggerProvider, HubLoggerProvider>(); options.AddProvider(new DatabaseLoggerProvider().Configure(logger => logger.UseSqlite(Configuration.GetConnectionString("Logging")))); }); // register database contexts services.AddDbContext <DefaultContext>(options => options.UseSqlite(Configuration.GetConnectionString("Default")), ServiceLifetime.Transient); services.AddDbContext <LogContext>(options => options.UseSqlite(Configuration.GetConnectionString("Logging")), ServiceLifetime.Transient); services.AddScoped <ISunDataService, SunDataService>(); services.AddScoped <ITriggerService, TriggerService>(); services.AddScoped <IActionExecutionService, ActionExecutionService>(); services.AddScoped <IEvaluateConditionService, EvaluateConditionService>(); services.AddSingleton <IZWaveAPIService, ZWaveAPIService>(); services.AddSingleton <IMessageStore, EmailReceiveService>(); services.AddSingleton <ITelldusAPIService, TelldusAPIService>(); services.AddSingleton <INotificationService, NotificationService>(); services.AddSingleton <IJsonDatabaseService, JsonDatabaseService>(); // add quartz after all services services.AddQuartz(); var options = new SmtpServerOptionsBuilder() .ServerName(Configuration["SMTP:ServerName"]) .Port(Configuration.GetValue <int>("SMTP:Port")) .Build(); services.AddSingleton(x => new SmtpServer.SmtpServer(options, x)); }
static async Task Main(string[] args) { System.Console.WriteLine("Resgrid Email Processor"); System.Console.WriteLine("-----------------------------------------"); Prime(); var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(25, 587) .MessageStore(new SampleMessageStore()) .Build(); var smtpServer = new SmtpServer.SmtpServer(options); await smtpServer.StartAsync(CancellationToken.None); }
public async Task Run() { int[] ports = this.ports.Split(",").Select(p => int.Parse(p)).ToArray(); SslProtocols sslProtocols = (SslProtocols)Enum.Parse(typeof(SslProtocols), this.sslProtocols); var optionsBuilder = new SmtpServerOptionsBuilder() .ServerName(this.serverName); foreach (int port in ports) { optionsBuilder.Endpoint(builder => { builder .AllowUnsecureAuthentication() .AuthenticationRequired() .Port(port); if (secure) { // this is important when dealing with a certificate that isnt valid ServicePointManager.ServerCertificateValidationCallback = IgnoreCertificateValidationFailureForTestingOnly; builder.Certificate(CreateCertificate(this.certificateFilePath, this.certificatePasswordFilePath)); } }); } var sp = new SmtpServer.ComponentModel.ServiceProvider(); sp.Add(new MailDamMessageStore()); sp.Add(new MailDamMailboxFilter()); sp.Add(new MailDamUserAuthenticator()); var options = optionsBuilder.Build(); var smtpServer = new SmtpServer.SmtpServer(options, sp); smtpServer.SessionCreated += OnSessionCreated; smtpServer.SessionCompleted += OnSessionCompleted; smtpServer.SessionFaulted += OnSessionFaulted; smtpServer.SessionCancelled += OnSessionCancelled; await smtpServer.StartAsync(CancellationToken.None); }
public Task StartAsync(EndpointDefinition smtpEndpoint) { if (this.IsActive) { return(Task.CompletedTask); } ServicePointManager.ServerCertificateValidationCallback = this.IgnoreCertificateValidationFailureForTestingOnly; this._currentEndpoint = smtpEndpoint; var options = new SmtpServerOptionsBuilder() .ServerName(this._applicationMetaData.AppName) .Endpoint( new EndpointDefinitionBuilder() .Endpoint(smtpEndpoint.ToIPEndPoint()) .IsSecure(false) .AllowUnsecureAuthentication(false) .Build()); this._server = this._smtpServerFactory(options.Build()); this._server.SessionCreated += this.OnSessionCreated; this._server.SessionCompleted += this.OnSessionCompleted; this._logger.Information("Starting Smtp Server on {IP}:{Port}...", this.ListenIpAddress, this.ListenPort); this._tokenSource = new CancellationTokenSource(); #pragma warning disable 4014 // server will block -- just let it run Task.Run( async() => { try { await this._server.StartAsync(this._tokenSource.Token); } catch (Exception ex) { this._logger.Error(ex, "Smtp Server Error"); } }, this._tokenSource.Token); #pragma warning restore 4014 return(Task.CompletedTask); }
public static void Run() { var cancellationTokenSource = new CancellationTokenSource(); var options = new SmtpServerOptionsBuilder() .ServerName("SmtpServer SampleApp") .Port(9025) .Build(); var server = new SmtpServer.SmtpServer(options); var serverTask = server.StartAsync(cancellationTokenSource.Token); SampleMailClient.Send(); cancellationTokenSource.Cancel(); serverTask.WaitWithoutException(); }
private static SmtpServer.SmtpServer CreateSmtpServer(MessageStore store) { // ReSharper disable once StringLiteralTypo var userAuthenticator = new UserAuthenticator("user1", "myPassw0rd"); IUserAuthenticatorFactory userAuthenticatorFactory = new UserAuthenticatorFactory(userAuthenticator); var options = new SmtpServerOptionsBuilder() .ServerName("localhost") .Port(25, 587) .MessageStore(store) .UserAuthenticator(userAuthenticatorFactory) .Build(); var smtpServer = new SmtpServer.SmtpServer(options); return(smtpServer); }
public static void Run() { var cancellationTokenSource = new CancellationTokenSource(); var options = new SmtpServerOptionsBuilder() .ServerName("SmtpServer SampleApp") .Port(9025) //.Endpoint(new EndpointDefinitionBuilder().Endpoint(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9025)).Build()) .Build(); var server = new SmtpServer.SmtpServer(options); var serverTask = server.StartAsync(cancellationTokenSource.Token); SampleMailClient.Send(); cancellationTokenSource.Cancel(); serverTask.WaitWithoutException(); }
/// <summary> /// Start a new server. /// </summary> /// <returns>The task to wait for</returns> public async Task Start() { this.Log.Info($"STARTING NEW SMTP SERVER ON {this.ServerName}:{string.Join(",", this.Ports)}"); var generateMessageStore = new GenerateMessageStore(); generateMessageStore.MessageReceived += (sender, message) => { this.MessageReceived?.Invoke(this, message); }; var options = new SmtpServerOptionsBuilder() .ServerName(this.ServerName) .Port(this.Ports) .MessageStore(generateMessageStore) .MailboxFilter(new AlwaysYesMailboxFilter()) .UserAuthenticator(new AlwaysYesAuthenticator()) .Build(); this._smtpServer = new SmtpServer(options); await this._smtpServer.StartAsync(CancellationToken.None); }
public static void Run() { _cancellationTokenSource = new CancellationTokenSource(); var options = new SmtpServerOptionsBuilder() .ServerName("SmtpServer SampleApp") .Port(9025) .Build(); var server = new SmtpServer.SmtpServer(options, ServiceProvider.Default); server.SessionCreated += OnSessionCreated; server.SessionCompleted += OnSessionCompleted; var serverTask = server.StartAsync(_cancellationTokenSource.Token); SampleMailClient.Send(); serverTask.WaitWithoutException(); }