public ReportController(MongoWrapper mongoWrapper, SmtpConfiguration smtpConfiguration, ILogger <ReportController> logger) { Logger = logger; Logger.LogTrace($"{nameof(ReportController)} Constructor Invoked"); MongoWrapper = mongoWrapper; SmtpConfiguration = smtpConfiguration; }
/// <summary> /// Tries to send a test mail via SMTP /// </summary> /// <param name="data">SMTP configuration to test</param> /// <returns>true, is the message was send successfully</returns> public bool SendTestMail(SmtpConfiguration data) { _logger.LogDebug("Testing SMTP configuration: {0}", data); // Create new client SmtpClient client = CreateSmtpClient(data); // Start a new message MailMessage message = CreateMessage(data); // Add the receiver message.To.Add(new MailAddress(data.ToMail)); // Set content message.Subject = "SMTP Test"; message.SubjectEncoding = Encoding.UTF8; message.IsBodyHtml = true; message.BodyEncoding = Encoding.UTF8; message.Body = DefaultTemplate.Html .Replace("%PNC_RULESURL%", "") .Replace("%PNC_TITLE%", "Great Success") .Replace("%PNC_BODY%", "<p>Hi there,</p><p>this is your Plastic-Notify-Center =)</p><p>Looks like the SMTP configuration is working. YEAH!</p>") .Replace("%PNC_TAGS%", "Awesome"); // Send the message client.Send(message); return(true); }
public void Execute(IJobExecutionContext context) { SmtpConfiguration smtpconfig = this._SmtpConfigurationRepository.FindDefault(); SmtpDeliveryMethod method = this.GetStmpDeliveryMethod(smtpconfig); SecurityProtocolType protocol = this.GetSecurityProtocolType(smtpconfig); foreach (Administrator admin in this._AdministratorRepository.FindAll()) { long executing = 0; long completed = 0; long failed = 0; foreach (Client client in this._ClientRepository.FindByAdmin(admin.ID)) { executing += this._BackupRepository.GetCount(client.ID, 0); completed += this._BackupRepository.GetCount(client.ID, 1); failed += this._BackupRepository.GetCount(client.ID, 2); } string subject = this._MailFactory.CreateSubject(); string message = this._MailFactory.CreateBody(executing, completed, failed); foreach (Email email in this._EmailRepository.Find(admin)) { this._MailSender.Send(smtpconfig.Server, smtpconfig.Port, smtpconfig.Username, smtpconfig.Password, smtpconfig.From, email.Address, subject, message, method, protocol); } } }
public async Task SendMeetingAsyncTest() { SendAccountConfiguration sendAccountConfiguration = new SendAccountConfiguration { Address = "TestAddress", DisplayName = "TestDisplayName" }; var directSendMailService = new DirectSendMailService(this.mockedClientPool.Object, this.mockedLogger.Object, sendAccountConfiguration); var emailMessage = new EmailMessage { Content = "TestContent", FromAddresses = new List <EmailAddress> { new EmailAddress { Address = "*****@*****.**", Name = "FromName" } }, ToAddresses = new List <EmailAddress> { new EmailAddress { Address = "*****@*****.**", Name = "ToName" } }, Subject = "emailSubject", }; var smtpConfig = new SmtpConfiguration { SmtpServer = "Test", SmtpPort = 25 }; this.mockedClientPool.Setup(x => x.GetClient(It.IsAny <Dictionary <string, string> >())).ReturnsAsync(this.mockedClient.Object); await directSendMailService.SendMeetingInviteAsync(emailMessage); this.mockedClient.Verify(x => x.SendAsync(It.Is <MimeMessage>(q => q.To.Mailboxes.Any(t => t.Address.Equals("*****@*****.**"))), It.IsAny <Dictionary <string, string> >(), null, default), Times.Once); this.mockedClient.Verify(x => x.SendAsync(It.Is <MimeMessage>(q => q.From.Mailboxes.Any(t => t.Address.Equals("*****@*****.**"))), It.IsAny <Dictionary <string, string> >(), null, default), Times.Once); this.mockedClient.Verify(x => x.SendAsync(It.Is <MimeMessage>(q => q.Subject.Equals("emailSubject")), It.IsAny <Dictionary <string, string> >(), null, default), Times.Once); }
public async Task UpdateConfiguration(SmtpConfiguration configuration) { PropertyInfo[] props = configuration.GetType().GetProperties(); foreach (var prop in props) { Config config = context.Configs.Where(x => x.Key == prop.Name).FirstOrDefault(); if (config == null) { config = new Config { Key = prop.Name, Value = (string)prop.GetValue(configuration) }; context.Configs.Add(config); } else { config.Value = (string)prop.GetValue(configuration); context.Configs.Update(config); } } bool connected = SmtpHelper.TestConnection(configuration.Host, int.Parse(configuration.Port)); if (!connected) { throw new FormMgrException("Smtp connection failed. Please enter a valid configuration."); } await context.SaveChangesAsync(); }
public async Task SendEmail(Form from) { string html = await _razorLightEngine.CompileRenderAsync <object>(Template, from); User user = await repository.GetUserById(from.SenderId); SmtpConfiguration configuration = await service.GetConfiguration(); Email.DefaultSender = new SmtpSender(new SmtpClient { Host = configuration.Host, Port = int.Parse(configuration.Port), Credentials = new NetworkCredential(configuration.Username, configuration.Password) }); SendResponse sendResponse = await Email .From(configuration.From) .To(configuration.To) .Subject($"New Message from: {user.Username}") .Body(html, true) .SendAsync(); if (!sendResponse.Successful) { //Todo log } }
public void Send(string receiverAddress, string subject, string content, SmtpConfiguration smtpConfiguration) { MimeMessage message = new MimeMessage(); message.To.Add(new MailboxAddress(receiverAddress)); message.From.Add(new MailboxAddress(smtpConfiguration.User)); message.Subject = subject; //We will say we are sending HTML. But there are options for plaintext etc. message.Body = new TextPart(TextFormat.Text) { Text = content }; //Be careful that the SmtpClient class is the one from Mailkit not the framework! using (var emailClient = new SmtpClient()) { //The last parameter here is to use SSL (Which you should!) emailClient.Connect(smtpConfiguration.Server, smtpConfiguration.Port, false); //Remove any OAuth functionality as we won't be using it. emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); emailClient.Authenticate(smtpConfiguration.User, smtpConfiguration.Pass); emailClient.Send(message); emailClient.Disconnect(true); } }
public static IServiceCollection AddSmtpInfrastructure( this IServiceCollection services, SmtpConfiguration configuration) { return(services .AddSingleton(CreateSmtpClient(configuration)) .AddSingleton <IEmailService, SmtpEmailService>()); }
/// <summary> /// Implementation of abstract method from NotifierBase to send a notification to each recipient /// </summary> /// <param name="data">SMTP notifier configuration data</param> /// <param name="message">Message to send</param> /// <param name="recipients">List of recipients</param> /// <returns></returns> protected override IEnumerable <Task> GetRecipientTasks(SmtpNotifierData data, Message message, IEnumerable <User> recipients) { // Prepare the config for the SMTP client SmtpConfiguration config = SmtpConfiguration.FromData(data); // Start a new task for each recipient return(recipients.Select(recipient => Task.Run(() => SendMessage(config, message, recipient)))); }
public OrdersController(IOrderService orders, IDeliveryDataService deliveryData, IOrderLogService logs, IMailService mails, IOptions <SmtpConfiguration> smtpConfiguration, IUserService users, ISettingsService settings) : base(users, settings) { this.orders = orders; this.deliveryData = deliveryData; this.logs = logs; this.mails = mails; this.smtpConfiguration = smtpConfiguration.Value; }
public DefaultRequestForQuotationFacade(IMailerService mailerService, IRfqPdfGenerator rfqPdfGenerator, IOptions <SmtpConfiguration> smtpConfiguration) { _mailerService = mailerService; _rfqPdfGenerator = rfqPdfGenerator; _smtpConfiguration = smtpConfiguration.Value; }
public EmailService(ISmtpHelper smtpHelper, IOptions <SmtpConfiguration> smtpConfiguration, IOptions <SendGridConfiguration> sendGridConfiguration) { _smtpHelper = smtpHelper; _smtpConfiguration = smtpConfiguration.Value; _sendGridConfiguration = sendGridConfiguration.Value; }
public RegisterUserControllerBase(MongoWrapper mongoWrapper, SmtpConfiguration smtpConfiguration, TokenConfigurations tokenConfigurations, SigningConfigurations signingConfigurations, ILogger <RegisterUserControllerBase <TBody> > logger) { Logger = logger; Logger.LogTrace($"{nameof(RegisterUserControllerBase<TBody>)} Constructor Invoked"); MongoWrapper = mongoWrapper; SmtpConfiguration = smtpConfiguration; TokenConfigurations = tokenConfigurations; SigningConfigurations = signingConfigurations; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services .AddTextFileEmployeeCatalog(FileConfiguration.From(Configuration)) .AddSmtpGreetingsNotification(SmtpConfiguration.From(Configuration)) .AddCore(); services.AddControllers(); }
public MailClient(SmtpConfiguration smtpConfiguration) { if (smtpConfiguration == null) { throw new ArgumentNullException(nameof(smtpConfiguration)); } _smtpConfiguration = smtpConfiguration; }
public void Send(SmtpConfiguration config, string to, string subject, string body, bool isBodyHtml = true) { using (var client = Build(config)) { var message = BuildMimeMessage(config.UserName, to, subject, body, isBodyHtml); client.Send(message); client.Disconnect(true); } }
/// <summary> /// Creates a new SmtpClient instance /// </summary> /// <param name="data">SMTP configuration</param> public SmtpClient CreateSmtpClient(SmtpConfiguration data) { var client = CreateSmtpClient(data.Host, data.Port, data.EnableSSL); // set credentials SetCredentials(client, data.Username, data.Password); return(client); }
public async Task SendAsync(SmtpConfiguration config, string to, string subject, string body, bool isBodyHtml = true) { using (var client = Build(config)) { var message = BuildMimeMessage(config.UserName, to, subject, body, isBodyHtml); await client.SendAsync(message); await client.DisconnectAsync(true); } }
public EmailSender(IOptions <SmtpConfiguration> smtpConfiguration, ISmtpClient smtpClient, ILogger <EmailSender> logger) { Guard.Against.Null(smtpConfiguration, nameof(smtpConfiguration)); Guard.Against.Null(smtpClient, nameof(smtpClient)); Guard.Against.Null(logger, nameof(logger)); _smtpConfiguration = smtpConfiguration.Value; _smtpClient = smtpClient; _logger = logger; }
public static async Task SendEmail(SmtpConfiguration smtpConfig, string body, string subject, Encoding encoding, MailAddress from, IEnumerable <MailAddress> to) { SmtpClient client = new SmtpClient { Port = smtpConfig.Port, Host = smtpConfig.Host, EnableSsl = true, Timeout = smtpConfig.Timeout, DeliveryMethod = SmtpDeliveryMethod.Network, DeliveryFormat = SmtpDeliveryFormat.International, UseDefaultCredentials = false, Credentials = new NetworkCredential ( smtpConfig.Email, smtpConfig.Password ), }; client.ServicePoint.Expect100Continue = true; client.ServicePoint.UseNagleAlgorithm = false; MailMessage mailMessage = new MailMessage() { BodyEncoding = Encoding.UTF8, DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure, From = from, BodyTransferEncoding = System.Net.Mime.TransferEncoding.Base64, IsBodyHtml = true, Sender = from, Subject = subject, Priority = MailPriority.Normal, SubjectEncoding = Encoding.UTF8, Body = body }; foreach (MailAddress address in to) { mailMessage.To.Add(address); } try { await client.SendMailAsync(mailMessage); } catch (Exception e) { LOGGER.Error(e, "Error while sending e-mail!"); throw; } }
public async Task ReturnClientTest() { var smtpConfig = new SmtpConfiguration { SmtpServer = "server", SmtpPort = 25 }; //mockedfactory.Setup(x => x.CreateClient(It.Is<ISmtpConfiguration>(t => t.SmtpPort == 25 && t.SmtpServer.Equals("server")), It.IsAny<ILogger>())).Returns(new Mock<IDSSmtpClient>().Object); var clientPool = new SmtpClientPool(smtpConfig, this.mockedLogger.Object, this.mockedfactory.Object); var client = new Mock <IDSSmtpClient>().Object; var dic = new Dictionary <string, string>(); await clientPool.ReturnClient(client, new Dictionary <string, string>()); }
private static ISmtpConfiguration CreateSmtpConfiguration(IComponentContext context) { var configuration = context.Resolve <IConfiguration>(); var result = new SmtpConfiguration(); new ConfigureFromConfigurationOptions <ISmtpConfiguration>(configuration.GetSection("Smtp")) .Configure(result); return(result); }
/// <summary> /// Get Agency SMTP Configuration Details /// </summary> /// <param name="agencyId"></param> /// <returns></returns> public SmtpConfiguration GetAgencySmtpConfiguration(Guid agencyId) { var smtpConfiguration = new SmtpConfiguration(); var agencyConfiguration = FindAgencyConfiguration(agencyId); if (agencyConfiguration != null) { smtpConfiguration = agencyConfiguration.SmtpConfiguration.As <SmtpConfiguration>(); } return(smtpConfiguration); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton(Configuration); services.AddSingleton((x) => { var smtpConfiguration = new SmtpConfiguration(); Configuration.GetSection("Smtp").Bind(smtpConfiguration); return(smtpConfiguration); }); services.AddScoped <MailSenderClient>(); services.AddControllersWithViews(); }
internal ConfigurationSmtpData Convert(SmtpConfiguration source) { ConfigurationSmtpData result = new ConfigurationSmtpData(); if (source != null) { result.Host = source.SmtpHost; result.Password = null; result.Port = source.SmtpPort; result.Username = source.SmtpUsername; } return(result); }
public SmtpEmailSender(SmtpConfiguration configuration, ILogger <EmailSender> logger) { _logger = logger; _configuration = configuration; _client = new SmtpClient { Host = _configuration.Host, Port = _configuration.Port, DeliveryMethod = SmtpDeliveryMethod.Network, EnableSsl = _configuration.UseSSL, Credentials = new System.Net.NetworkCredential(_configuration.Login, _configuration.Password) }; }
protected virtual void ConfigureClient(SmtpClient client, SmtpConfiguration config) { client.Connect( config.Host, config.Port, GetSecureSocketOption(config.EnableSsl) ); client.Authenticate( config.UserName, config.Password ); }
public SmtpConfiguration GetSmtpConfiguration() { var configuration = new SmtpConfiguration { FromTitle = appSettings["FromTitle"], Login = appSettings["Login"], Password = appSettings["Password"], Port = int.Parse(appSettings["Port"]), Server = appSettings["Server"], SSL = bool.Parse(appSettings["SSL"]) }; return(configuration); }
protected SmtpDeliveryMethod GetStmpDeliveryMethod(SmtpConfiguration config) { switch (config.Method) { case 1: return(SmtpDeliveryMethod.SpecifiedPickupDirectory); case 2: return(SmtpDeliveryMethod.PickupDirectoryFromIis); default: return(SmtpDeliveryMethod.Network); } }
public void UpdateSmtpConfiguration(Guid agencyId, SmtpConfiguration smtpConfiguration) { RequiresAgencyAdmin(agencyId); var agencyConfigurations = UnitOfWork.GetEntityQuery <AgencyConfiguration>() .FirstOrDefault(c => c.Agency.Id == agencyId); if (agencyConfigurations == null) { return; } smtpConfiguration.MapInto(agencyConfigurations.SmtpConfiguration); UnitOfWork.Commit(); }