예제 #1
0
 public NotificationService(ISmtpClient mailer)
 {
     _sender = Config.SmtpFromAddress;
     _recipient = Config.SmtpNotificationRecipient.Replace(';',',');
     _subject = string.Format("Salsa Sync Notification ({0})", Config.Environment);
     _mailer = mailer;
 }
예제 #2
0
 public SmtpEmailService(ISmtpClient smtpClient)
 {
     using (Logger.Assembly.Scope())
     {
         _smtpClient = smtpClient;
     }
 }
예제 #3
0
 /// <summary>
 /// Sends a MailMessage using smtpClient
 /// </summary>
 /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param>
 public virtual void Send(ISmtpClient smtpClient = null)
 {
     smtpClient = smtpClient ?? GetSmtpClient();
     using (smtpClient)
     {
         smtpClient.Send(this);
     }
 }
 /// <summary>
 /// Asynchronously Sends a MailMessage using smtpClient
 /// </summary>
 /// <param name="userState">The userState</param>
 /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param>
 public virtual async Task SendAsync(object userState = null, ISmtpClient smtpClient = null)
 {
     await Task.Run(() =>
         {
             smtpClient = smtpClient ?? GetSmtpClient();
             smtpClient.SendAsync(this, userState);
         });
 }
예제 #5
0
 /// <summary>
 /// Sends a MailMessage using smtpClient
 /// </summary>
 /// <param name="message">The mailMessage Object</param>
 /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param>
 public static void Send(this MailMessage message, ISmtpClient smtpClient = null)
 {
     smtpClient = smtpClient ?? GetSmtpClient();
     using (smtpClient)
     {
         smtpClient.Send(message);
     }
 }
		public EmailDeliveryMethod(ISmtpClient smtpClient, MailSettings mailSettings)
		{
			if (smtpClient == null)
				throw new ArgumentNullException("smtpClient");
			
			SmtpClient = smtpClient;
			MailSettings = mailSettings;
		}
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="config">The config.</param>
 /// <param name="smtpClient">The SMTP client.</param>
 /// <param name="repository">The repository.</param>
 /// <param name="attachmentFileSystem">The attachment file system.</param>
 /// <param name="staticOverridesesProvider">The static overrideses provider.</param>
 public MailMessageDequeuer(IMailMessageSenderConfig config, ISmtpClient smtpClient, IRepository<EmailQueueItem> repository, IAttachmentFileSystem attachmentFileSystem, IStaticOverridesProvider staticOverridesesProvider)
 {
     Config = config;
     Repository = repository;
     StaticOverridesesProvider = staticOverridesesProvider;
     AttachmentFileSystem = attachmentFileSystem;
     SmtpClient = smtpClient;
     
 }
예제 #8
0
 public CpuObserver(ISettingsService<AlertSettingsDto> settings, IEventService eventService, ISmtpClient client, IFile file, ILogger logger)
     : base(logger)
 {
     SettingsService = settings;
     EventService = eventService;
     SmtpClient = client;
     ConfigurationReader = new ConfigurationReader(SettingsService, AlertTypeDto.Cpu);
     Notifier = new Notifier(ConfigurationReader.Read().Intervals.CriticalNotification, eventService, client, file, logger, AlertTypeDto.Cpu);
 }
예제 #9
0
        public FilteringSmtpClient(ISmtpClient delegateTo, string overridingRecipient, string[] whitelist)
            : this(delegateTo)
        {
            this.overridingRecipient = new MailAddress(overridingRecipient);

            foreach (string mailAddress in whitelist)
            {
                this.whitelist.Add(new MailAddress(mailAddress));
            }
        }
예제 #10
0
파일: Notifier.cs 프로젝트: NZBDash/NZBDash
 public Notifier(TimeSpan interval, IEventService eventService, ISmtpClient client, IFile file, ILogger logger, AlertTypeDto type)
 {
     Interval = interval;
     EventService = eventService;
     SmtpClient = client;
     File = file;
     Logger = logger;
     Sendy = new EmailSender(file, logger, client);
     AlertType = type;
 }
예제 #11
0
        /// <summary>
        /// Asynchronously Sends a MailMessage using smtpClient
        /// </summary>
        /// <param name="message">The mailMessage Object</param>
        /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param>
        public static void SendAsync(this MailMessage message, ISmtpClient smtpClient = null)
        {
            smtpClient = smtpClient ?? GetSmtpClient();
            var userState = "userState";

            using (smtpClient)
            {
                smtpClient.SendAsync(message, userState);
            }
        }
예제 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EmailNotification" /> class.
        /// </summary>
        /// <param name="stamp">Add text to email message with DateTime</param>
        /// <param name="smtpClient">SmtpClient to send email with</param>
        public EmailNotification(bool stamp, ISmtpClient smtpClient)
        {
            if (smtpClient == null)
            {
                throw new ArgumentNullException("iSmtpClient");
            }

            this.NotificationSent = false;
            this.StampEmailWithTime = stamp;
            this.SmtpClient = smtpClient;
        }
        internal MailSender(
            ISmtpClient smtpClient,
            MailSenderConfiguration configuration)
        {
            if (smtpClient == null)
                throw new ArgumentNullException("smtpClient");
            
            if (configuration != null)
                ConfigureSmtpClient(smtpClient, configuration);

            this.smtpClient = smtpClient;
        }
        public UserAdministrationController(
			IMembershipSettings membershipSettings,
			IUserService userService,
			IPasswordService passwordService,
			IRolesService rolesService,
			ISmtpClient smtpClient)
        {
            _membershipSettings = membershipSettings;
            _userService = userService;
            _passwordService = passwordService;
            _rolesService = rolesService;
            _smtpClient = smtpClient;
        }
예제 #15
0
 /// <summary>
 /// Transport created to deliver messages to SendGrid using SMTP
 /// </summary>
 /// <param name="client">SMTP client we are wrapping</param>
 /// <param name="credentials">Sendgrid user credentials</param>
 /// <param name="host">MTA recieving this message.  By default, sent through SendGrid.</param>
 /// <param name="port">SMTP port 25 is the default.  Port 465 can be used for Secure SMTP.</param>
 private SMTP(ISmtpClient client, NetworkCredential credentials, string host = SmtpServer, int port = Port)
 {
     _client = client;
     switch (port)
     {
         case Port:
             break;
         case SslPort:
             _client.EnableSsl = true;
             break;
         case TlsPort:
             throw new NotSupportedException("TLS not supported");
     }
 }
 internal void ConfigureSmtpClient(
     ISmtpClient smtpClient, 
     MailSenderConfiguration configuration)
 {
     if (configuration.Host != null)
         smtpClient.Host = configuration.Host;
     if (configuration.Port.HasValue)
         smtpClient.Port = configuration.Port.Value;
     if (configuration.EnableSsl.HasValue)
         smtpClient.EnableSsl = configuration.EnableSsl.Value;
     if (configuration.DeliveryMethod.HasValue)
         smtpClient.DeliveryMethod = configuration.DeliveryMethod.Value;
     if (configuration.UseDefaultCredentials.HasValue)
         smtpClient.UseDefaultCredentials = configuration.UseDefaultCredentials.Value;
     if (configuration.Credentials != null)
         smtpClient.Credentials = configuration.Credentials;
     if (configuration.PickupDirectoryLocation != null)
         smtpClient.PickupDirectoryLocation = configuration.PickupDirectoryLocation;
 }
예제 #17
0
        public FilteringSmtpClient(ISmtpClient delegateTo)
        {
            QMailConfigurationSection config = (QMailConfigurationSection)ConfigurationManager.GetSection("qmailConfiguration");
            FilterElement filter = config.Filter;

            this.delegateTo = delegateTo;
            string to = filter.OverrideTo; // ConfigHelper.DefaultString("qmail.mail.to", null);
            if (!string.IsNullOrEmpty(to))
            {
                overridingRecipient = new MailAddress(to);
            }

            ToMailAddressElementCollection mailAddresses = filter.Whitelist;

            for (int n = 0; n < mailAddresses.Count; n++)
            {
                string mailAddress = mailAddresses[n].MailAddress;
                whitelist.Add(new MailAddress(mailAddress));
            }
        }
예제 #18
0
        public MailSenderService(IMailQueue queue, IConfiguration configuration = null, ISmtpClient smtpClient = null)
        {
            if (queue == null) throw new ArgumentException("Queue cannot be null.", "queue");

            m_configuration = configuration ?? new DefaultConfiguration();
            m_queue = queue;
            m_smtpClient = smtpClient;

            s_sleepAfterException = StringToIntUtil.Interpret(m_configuration.GetValue(APP_KEY_WAIT_ERROR), s_sleepAfterException);
            s_sleepAfterOnNoWork = StringToIntUtil.Interpret(m_configuration.GetValue(APP_KEY_WAIT_NOWORK), s_sleepAfterOnNoWork);

            s_overrideRecipient = m_configuration.GetValue(APP_KEY_OVERRIDE_RECIPIENT);
            s_overrideSmtpHost = m_configuration.GetValue(APP_KEY_OVERRIDE_SMTP_HOST);
            s_overrideSmtpPort = StringToIntUtil.InterpretNullable(m_configuration.GetValue(APP_KEY_OVERRIDE_SMTP_PORT), null);
            s_overrideSmtpSSL = StringToBoolUtil.InterpretNullable(m_configuration.GetValue(APP_KEY_OVERRIDE_SMTP_SSL), null);
            s_overrideSmtpUser = m_configuration.GetValue(APP_KEY_OVERRIDE_SMTP_USER);
            s_overrideSmtpPassword = m_configuration.GetValue(APP_KEY_OVERRIDE_SMTP_PASSWORD);
            s_overrideSmtpDomain = m_configuration.GetValue(APP_KEY_OVERRIDE_SMTP_DOMAIN);

        }
 public void SetUp()
 {
     var mock = new Mock<ISmtpClient>();
       mock.Setup(x => x.Send(It.IsAny<MailMessage>()));
       smtpClient = mock.Object;
 }
예제 #20
0
        private void ConfigureMailClient( LogEventInfo lastEvent, ISmtpClient client )
        {
            client.Host = this.SmtpServer.Render( lastEvent );
            client.Port = this.SmtpPort;
            client.EnableSsl = this.EnableSsl;

            if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
            {
                InternalLogger.Trace( "  Using NTLM authentication." );
                client.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
            {
                string username = this.SmtpUserName.Render( lastEvent );
                string password = this.SmtpPassword.Render( lastEvent );

                InternalLogger.Trace( "  Using basic authentication: Username='******' Password='******'", username, new string( '*', password.Length ) );
                client.Credentials = new NetworkCredential( username, password );
            }
        }
예제 #21
0
 public Mailer(ISmtpClient smtpClient)
 {
     this._smtpClient = smtpClient;
 }
예제 #22
0
 /// <summary>
 /// Asynchronously Sends a MailMessage using smtpClient
 /// </summary>
 /// <param name="userState">The userState</param>
 /// <param name="smtpClient">leave null to use default System.Net.Mail.SmtpClient</param>
 public virtual void SendAsync(object userState = null, ISmtpClient smtpClient = null)
 {
     smtpClient = smtpClient ?? GetSmtpClient();
     smtpClient.SendAsync(this, userState);
 }
예제 #23
0
 /// <summary>
 /// For Unit Testing Only!
 /// </summary>
 /// <param name="client"></param>
 /// <param name="credentials"></param>
 /// <param name="host"></param>
 /// <param name="port"></param>
 /// <returns></returns>
 internal static SMTP GetInstance(ISmtpClient client, NetworkCredential credentials, string host = SmtpServer, Int32 port = Port)
 {
     return(new SMTP(client, credentials, host, port));
 }
예제 #24
0
 public OrderMailService(ISmtpClient smtpClient, ILogger logger)
 {
     this._logger     = logger;
     this._smtpClient = smtpClient;
 }
예제 #25
0
 public ServiceClass(ISmtpClient smtpClient)
 {
     //ServiceClass uses this dependency
     _smtpClient = smtpClient;
 }
 public MailService(IConfiguration configuration, ISmtpClient smtpClient)
 {
     Configuration = configuration;
     SmtpClient    = smtpClient;
 }
 public UserAdministrationController(AspNetMembershipProviderWrapper membership, IRolesService roles, ISmtpClient smtp)
     : this(membership.Settings, membership, membership, roles, smtp)
 {
 }
예제 #28
0
 public SendTellAFriendMailCommandHandler(ISmtpClient mailClient)
 {
     _mailClient = mailClient;
 }
예제 #29
0
 public EMailSender(IConfiguration configuration, ISmtpClient client)
 {
     _emailSourceAddress = configuration.GetSection("emailConfig")["sourceAddress"];
     _client             = client;
 }
예제 #30
0
 public Example2b()
 {
     client = new SmtpClientEx("smtp.somehost.com", 465);
 }
예제 #31
0
 public OrderMailService(ISmtpClient smtpClient)
 {
     this._smtpClient = smtpClient;
 }
예제 #32
0
 public OrdersScheduler(ILogger <OrdersScheduler> logger, IConfiguration config)
 {
     _logger     = logger;
     _config     = config;
     _smtpClient = new SmtpClient();
 }
 public UserAdministrationController(AspNetMembershipProviderWrapper membership, IRolesService roles, ISmtpClient smtp)
     : this(membership.Settings, membership, membership, roles, smtp)
 {
 }
예제 #34
0
 /// <summary>
 /// For Unit Testing Only!
 /// </summary>
 /// <param name="client"></param>
 /// <param name="credentials"></param>
 /// <param name="host"></param>
 /// <param name="port"></param>
 /// <returns></returns>
 internal static SMTP GetInstance(ISmtpClient client, NetworkCredential credentials, String host = SmtpServer, Int32 port = Port)
 {
     return new SMTP(client, credentials, host, port);
 }
 public EmailService(ISmtpClient smtpClient)
 {
     _smtpClient = smtpClient;           
 }
예제 #36
0
 public MailService(IOptions <MailSettings> mailSettings, ISmtpClient smtpClient)
 {
     _mailSettings = mailSettings.Value;
     _smtpClient   = smtpClient;
 }
예제 #37
0
 public EmailNotifier(SmtpClientFactory smtpFactory)
 {
     _client = smtpFactory.CreateClient();
 }
 /// <summary>
 /// Provider for authenticating admins
 /// </summary>
 /// <param name="context"></param>
 public AdminAuthenticationProvider(FlexinetsContext context, IConfiguration configuration, ISmtpClient smtpClient)
 {
     _context    = context;
     _smtpClient = smtpClient;
     // todo refactor
     _resetReturnDomains = new[]
     {
         "https://secure.flexinets.se",
         "https://wifi.flexinets.se",
         "https://globalwifi.flexinets.se",
         "https://portal.flexinets.se"
     };
 }
예제 #39
0
파일: MailTarget.cs 프로젝트: shadowca/NLog
        /// <summary>
        /// Set properties of <paramref name="client"/>
        /// </summary>
        /// <param name="lastEvent">last event for username/password</param>
        /// <param name="client">client to set properties on</param>
        internal void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client)
        {
            CheckRequiredParameters();

            if (this.SmtpServer == null && string.IsNullOrEmpty(this.PickupDirectoryLocation))
            {
                throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer/PickupDirectoryLocation"));
            }

            if (this.DeliveryMethod == SmtpDeliveryMethod.Network && this.SmtpServer == null)
            {
                throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer"));
            }
            
            if (this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(this.PickupDirectoryLocation))
            {
                throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation"));
            }

            if (this.SmtpServer != null && this.DeliveryMethod == SmtpDeliveryMethod.Network)
            {
                var renderedSmtpServer = this.SmtpServer.Render(lastEvent);
                if (string.IsNullOrEmpty(renderedSmtpServer))
                {
                    throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer" ));
                }

                client.Host = renderedSmtpServer;
                client.Port = this.SmtpPort;
                client.EnableSsl = this.EnableSsl;

                if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
                {
                    InternalLogger.Trace("  Using NTLM authentication.");
                    client.Credentials = CredentialCache.DefaultNetworkCredentials;
                }
                else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
                {
                    string username = this.SmtpUserName.Render(lastEvent);
                    string password = this.SmtpPassword.Render(lastEvent);

                    InternalLogger.Trace("  Using basic authentication: Username='******' Password='******'", username, new string('*', password.Length));
                    client.Credentials = new NetworkCredential(username, password);
                }

            }

            if (!string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
            {
                client.PickupDirectoryLocation = this.PickupDirectoryLocation;
            }

            // In case DeliveryMethod = PickupDirectoryFromIis we will not require Host nor PickupDirectoryLocation
            client.DeliveryMethod = this.DeliveryMethod;
            client.Timeout = this.Timeout;

            
        }
예제 #40
0
 public EmailSender(IFile file, ILogger logger, ISmtpClient client)
 {
     File = file;
     Logger = logger;
     Client = client;
 }
예제 #41
0
 public EMailServiceSender(ISmtpClient smtpClient, SmtpMailMessage message)
 {
     _smtpClient = smtpClient;
     _message    = message;
 }
예제 #42
0
        /// <summary>
        /// Set propertes of <paramref name="client"/>
        /// </summary>
        /// <param name="lastEvent">last event for username/password</param>
        /// <param name="client">client to set properties on</param>
        private void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client)
        {

            CheckRequiredParameters();

            var renderedSmtpServer = this.SmtpServer.Render(lastEvent);
            if (string.IsNullOrEmpty(renderedSmtpServer))
            {
                throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer"));
            }
            client.Host = renderedSmtpServer;
            client.Port = this.SmtpPort;
            client.EnableSsl = this.EnableSsl;
            client.Timeout = this.Timeout;

            if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
            {
                InternalLogger.Trace("  Using NTLM authentication.");
                client.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
            {
                string username = this.SmtpUserName.Render(lastEvent);
                string password = this.SmtpPassword.Render(lastEvent);

                InternalLogger.Trace("  Using basic authentication: Username='******' Password='******'", username, new string('*', password.Length));
                client.Credentials = new NetworkCredential(username, password);
            }
        }
예제 #43
0
        /// <summary>
        /// Sends batch of <see cref="QueuedEmail"/>.
        /// </summary>
        /// <param name="batch">Current batch of <see cref="QueuedEmail"/></param>
        /// <param name="client"><see cref="ISmtpClient"/> to use for sending mails.</param>
        /// <param name="saveToDisk">Specifies whether mails should be saved to disk.</param>
        /// <returns></returns>
        private async Task <bool> ProcessMailBatchAsync(IEnumerable <QueuedEmail> batch, ISmtpClient client, bool saveToDisk, CancellationToken cancelToken = default)
        {
            var result = false;

            foreach (var queuedEmail in batch)
            {
                if (cancelToken.IsCancellationRequested)
                {
                    break;
                }

                try
                {
                    using var msg = ConvertMail(queuedEmail);

                    if (saveToDisk)
                    {
                        await _mailService.SaveAsync(_emailAccountSettings.PickupDirectoryLocation, msg);
                    }
                    else
                    {
                        await client.SendAsync(msg, cancelToken);

                        if (_emailAccountSettings.MailSendingDelay > 0)
                        {
                            await Task.Delay(_emailAccountSettings.MailSendingDelay, cancelToken);
                        }
                    }

                    queuedEmail.SentOnUtc = DateTime.UtcNow;
                    result = true;
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, string.Concat(T("Admin.Common.ErrorSendingEmail"), ": ", ex.Message));
                    result = false;
                }
                finally
                {
                    queuedEmail.SentTries += 1;
                }
            }

            return(result);
        }
예제 #44
0
 public Example2b(ISmtpClient client)
 {
     this.client = client;
 }
예제 #45
0
        private void ProcessSingleMailMessage(List <AsyncLogEventInfo> events)
        {
            try
            {
                LogEventInfo firstEvent = events[0].LogEvent;
                LogEventInfo lastEvent  = events[events.Count - 1].LogEvent;

                // unbuffered case, create a local buffer, append header, body and footer
                var bodyBuffer = new StringBuilder();
                if (this.Header != null)
                {
                    bodyBuffer.Append(this.Header.Render(firstEvent));
                    if (this.AddNewLines)
                    {
                        bodyBuffer.Append("\n");
                    }
                }

                foreach (AsyncLogEventInfo eventInfo in events)
                {
                    bodyBuffer.Append(this.Layout.Render(eventInfo.LogEvent));
                    if (this.AddNewLines)
                    {
                        bodyBuffer.Append("\n");
                    }
                }

                if (this.Footer != null)
                {
                    bodyBuffer.Append(this.Footer.Render(lastEvent));
                    if (this.AddNewLines)
                    {
                        bodyBuffer.Append("\n");
                    }
                }

                using (var msg = new MailMessage())
                {
                    this.SetupMailMessage(msg, lastEvent);
                    msg.Body = bodyBuffer.ToString();

                    using (ISmtpClient client = this.CreateSmtpClient())
                    {
                        client.Host      = this.SmtpServer.Render(lastEvent);
                        client.Port      = this.SmtpPort;
                        client.EnableSsl = this.EnableSsl;

                        InternalLogger.Debug("Sending mail to {0} using {1}:{2} (ssl={3})", msg.To, client.Host, client.Port, client.EnableSsl);
                        InternalLogger.Trace("  Subject: '{0}'", msg.Subject);
                        InternalLogger.Trace("  From: '{0}'", msg.From.ToString());
                        if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
                        {
                            InternalLogger.Trace("  Using NTLM authentication.");
                            client.Credentials = CredentialCache.DefaultNetworkCredentials;
                        }
                        else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
                        {
                            string username = this.SmtpUserName.Render(lastEvent);
                            string password = this.SmtpPassword.Render(lastEvent);

                            InternalLogger.Trace("  Using basic authentication: Username='******' Password='******'", username, new string('*', password.Length));
                            client.Credentials = new NetworkCredential(username, password);
                        }

                        client.Send(msg);

                        foreach (var ev in events)
                        {
                            ev.Continuation(null);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                foreach (var ev in events)
                {
                    ev.Continuation(exception);
                }
            }
        }