示例#1
0
        public async Task <IActionResult> TestEmailConfig([FromBody] EmailConfigModel model)
        {
            if (model == null)
            {
                return(InvalidRequest());
            }

            var testEmailConfigModel = new TestEmailConfigModel
            {
                EmailAddress = model.SmtpEmailAddress,
                Password     = model.SmtpPassword,
                Port         = model.SmtpPort,
                Server       = model.SmtpServer,
                User         = model.SmtpUser,
                EnableSSL    = model.SmtpEnableSSL
            };

            var result = await this.EmailService.TestEmailConfig(testEmailConfigModel);

            if (result.Success)
            {
                return(this.Success());
            }
            else
            {
                return(this.Error(result.ErrorMessage));
            }
        }
示例#2
0
        public MailSender(EmailConfigModel emailConfig)
        {
            if (emailConfig == null)
            {
                throw new ArgumentNullException(nameof(emailConfig));
            }

            EmailConfig = emailConfig;
        }
示例#3
0
        public string SaveEmailConfig(EmailConfigModel emailConfigModel)
        {
            List <KeyValuePair <string, object> > param = new List <KeyValuePair <string, object> >()
            {
                new KeyValuePair <string, object>("@ConfigName", emailConfigModel.ConfigName),
                new KeyValuePair <string, object>("@ServerName", emailConfigModel.ServerName),
                new KeyValuePair <string, object>("@Port", emailConfigModel.Port),
                new KeyValuePair <string, object>("@Username", emailConfigModel.UserName),
                new KeyValuePair <string, object>("@Password", emailConfigModel.Password),
                new KeyValuePair <string, object>("@UserId", emailConfigModel.UserId),
            };

            return(DataExecutor.ExecuteScalar(UtilityConstant.Procedures.Mst_SaveEmailConfig, param));
        }
        public static IServiceProvider ConfigureServices()
        {
            var configuration = GetConfiguration();

            IServiceCollection service = new ServiceCollection();

            var emailSettings = configuration.GetSection("emailSettings");
            var fromAddress   = emailSettings.GetValue <string>("FromAddress");
            var toAddress     = emailSettings.GetValue <string>("ToAddress");
            var username      = emailSettings.GetValue <string>("Username");
            var password      = emailSettings.GetValue <string>("Password");
            var subject       = emailSettings.GetValue <string>("Subject");
            var smtpServer    = emailSettings.GetValue <string>("SmtpServer");
            var port          = emailSettings.GetValue <int>("Port");

            var quoteSettings = configuration.GetSection("quoteSettings");
            var fileName      = quoteSettings.GetValue <string>("FileName");

            var emailConfig = new EmailConfigModel
            {
                FromAddress = fromAddress,
                ToAddress   = toAddress,
                Username    = username,
                Password    = password,
                Subject     = subject,
                SmtpServer  = smtpServer,
                Port        = port
            };

            var validators = new List <AbstractValidator <InputModel> >
            {
                new ValueValidator(),
                new DateValidator()
            };

            service.AddSingleton <IInputValidator, InputValidator>(x => new InputValidator(validators));
            service.AddSingleton <ICsvFileReader, CsvFileReader>(x => new CsvFileReader());
            service.AddSingleton <IRepository, CsvQuoteRepository>(x => new CsvQuoteRepository(new CsvFileReader(), fileName));
            service.AddSingleton <IStrategyResolver, StrategyResolver>(x => new StrategyResolver());
            service.AddSingleton <IQuoteService, QuoteService>(x => new QuoteService(new CsvQuoteRepository(new CsvFileReader(), fileName), new StrategyResolver()));
            service.AddSingleton <IInputValidator, InputValidator>(x => new InputValidator(new List <AbstractValidator <InputModel> >()));
            service.AddSingleton <IAppController, AppController>(x => new AppController(new QuoteService(new CsvQuoteRepository(new CsvFileReader(), fileName), new StrategyResolver()), new EmailService(emailConfig), new InputValidator(validators)));

            service.AddSingleton <IEmailService, EmailService>(x => new EmailService(emailConfig));

            var provider = service.BuildServiceProvider();

            return(provider);
        }
示例#5
0
        public async Task <IActionResult> SaveEmailConfig([FromBody] EmailConfigModel model)
        {
            if (model == null || !ModelState.IsValid)
            {
                return(InvalidRequest());
            }

            var config = await ConfigService.Get();

            Mapper.Map(model, config);

            await ConfigService.Save(config);

            return(Success());
        }
示例#6
0
        public async Task <IActionResult> Notice()
        {
            EmailConfigModel model = new EmailConfigModel();
            IJobDetail       job   = await _scheduler.GetJobDetail(new JobKey(EmailJobKeys.NameKey, EmailJobKeys.GroupKey));

            if (job != null)
            {
                model.Host        = job.JobDataMap.GetString(EmailJobKeys.Host);
                model.Port        = job.JobDataMap.GetInt(EmailJobKeys.Port);
                model.UserName    = job.JobDataMap.GetString(EmailJobKeys.UserName);
                model.Password    = job.JobDataMap.GetString(EmailJobKeys.Password);
                model.To          = job.JobDataMap.GetString(EmailJobKeys.To);
                model.NickName    = job.JobDataMap.GetString(EmailJobKeys.NickName);
                model.CacheExpiry = job.JobDataMap.GetInt(EmailJobKeys.CacheExpiry);
            }
            return(View(model));
        }
示例#7
0
        public async Task Notice(EmailConfigModel request)
        {
            JobKey     key     = new JobKey(EmailJobKeys.NameKey, EmailJobKeys.GroupKey);
            JobDataMap dataMap = new JobDataMap();

            dataMap.Put(EmailJobKeys.Host, request.Host);
            dataMap.Put(EmailJobKeys.Port, request.Port);
            dataMap.Put(EmailJobKeys.UserName, request.UserName);
            dataMap.Put(EmailJobKeys.Password, request.Password);
            dataMap.Put(EmailJobKeys.To, request.To);
            dataMap.Put(EmailJobKeys.NickName, request.NickName);
            dataMap.Put(EmailJobKeys.CacheExpiry, request.CacheExpiry);
            IJobDetail job = JobBuilder.Create <HttpJob>()
                             .StoreDurably(true)
                             .RequestRecovery()
                             .WithDescription("邮件通知配置Job,切勿删除")
                             .WithIdentity(key)
                             .UsingJobData(dataMap)
                             .Build();
            await _scheduler.AddJob(job, true);   // 更新邮件通知配置
        }
示例#8
0
        public async Task SendEmailAsync(EmailMessage emailMessage)
        {
            EmailConfigModel emailConfig = _config.GetSection("EmailSmtpConfig").Get <EmailConfigModel>();
            var message = new MimeMessage();

            message.From.Add(MailboxAddress.Parse(emailMessage.From));
            message.To.Add(MailboxAddress.Parse(emailMessage.To));
            message.Subject = emailMessage.Subject;
            message.Body    = new TextPart(TextFormat.Html)
            {
                Text = emailMessage.Body
            };

            using var emailClient = new SmtpClient();
            emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
            await emailClient.ConnectAsync(emailConfig.SmtpServer, emailConfig.SmtpPort, false).ConfigureAwait(false);

            await emailClient.AuthenticateAsync(emailConfig.SmtpUsername, emailConfig.SmtpPassword).ConfigureAwait(false);

            await emailClient.SendAsync(message).ConfigureAwait(false);

            await emailClient.DisconnectAsync(true).ConfigureAwait(false);
        }
示例#9
0
        public void SendMail()
        {
            var config = new EmailConfigModel
            {
                Host     = "smtp2.materalcmx.com",
                UserName = "******",
                Password = "******"
            };
            var          cacheManager  = new EmailManager(config);
            const string address       = "*****@*****.**";
            const string displayName   = "Materal";
            const string title         = "测试邮件标题";
            const string body          = "<div><p>测试邮件体</p></div>";
            var          targetAddress = new []
            {
                "*****@*****.**"
            };
            var ccAddress = new []
            {
                "*****@*****.**"
            };

            cacheManager.SendMail(address, displayName, title, body, targetAddress, ccAddress, Encoding.UTF8);
        }
示例#10
0
        public JsonResult SendMessage(string name, string email, string message)
        {
            try
            {
                var retorno = "OK";
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(message))
                {
                    //Obtener configuración
                    EmailConfigModel tmp = GetEmailConfig();

                    var mess = new MimeMessage();
                    mess.From.Add(new MailboxAddress(tmp.NameFrom, tmp.NameAuth));
                    mess.To.Add(new MailboxAddress(tmp.MailboxToName, tmp.MailboxToAddr));
                    mess.Subject = tmp.Subject + name + " <" + email + ">";

                    mess.Body = new TextPart("plain")
                    {
                        Text = message
                    };

                    using (var client = new SmtpClient())
                    {
                        // For suport all SSL certificates (including StartTls)
                        client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                        //client.CheckCertificateRevocation = false;

                        try
                        {
                            client.Connect(tmp.Host, tmp.Port, true);
                        }
                        catch (SmtpCommandException ex)
                        {
                            retorno = ex.Message + ". " + ex.InnerException?.Message;
                            _log.LogError(retorno);
                            return(Json(retorno));
                        }
                        catch (SmtpProtocolException ex)
                        {
                            retorno = $"Protocol error while trying to connect: {ex.Message}";
                            _log.LogError(retorno);
                            return(Json(retorno));
                        }

                        if (client.Capabilities.HasFlag(SmtpCapabilities.Authentication))
                        {
                            try
                            {
                                client.Authenticate(tmp.NameAuth, tmp.PasswAuth);
                            }
                            catch (AuthenticationException)
                            {
                                retorno = $"Invalid user name or password.";
                                _log.LogError(retorno);
                                return(Json(retorno));
                            }
                            catch (SmtpCommandException ex)
                            {
                                retorno = $"Error trying to authenticate: {ex.Message}";
                                _log.LogError(retorno);
                                return(Json(retorno));
                            }
                            catch (SmtpProtocolException ex)
                            {
                                retorno = $"Protocol error while trying to authenticate: {ex.Message}";
                                _log.LogError(retorno);
                                return(Json(retorno));
                            }
                        }

                        try
                        {
                            client.Send(mess);
                        }
                        catch (SmtpCommandException ex)
                        {
                            retorno = $"Error sending message: {ex.Message}\tStatusCode: {ex.StatusCode}";
                            switch (ex.ErrorCode)
                            {
                            case SmtpErrorCode.RecipientNotAccepted:
                                retorno += $"\tRecipient not accepted: {ex.Mailbox}";
                                break;

                            case SmtpErrorCode.SenderNotAccepted:
                                retorno += $"\tSender not accepted: {ex.Mailbox}";
                                break;

                            case SmtpErrorCode.MessageNotAccepted:
                                retorno += "\tMessage not accepted.";
                                break;
                            }
                            _log.LogError(retorno);
                        }
                        catch (SmtpProtocolException ex)
                        {
                            retorno = $"Protocol error while sending message: {ex.Message}";
                            _log.LogError(retorno);
                        }
                        client.Disconnect(true);
                    }
                }
                else
                {
                    retorno = "No enviado, parámetros erroneos.";
                }
                return(Json(retorno));
            }
            catch (System.Exception ex)
            {
                return(Json(ex.Message));
            }
        }
示例#11
0
 public Task <IActionResult> SaveEmailConfig([FromBody] EmailConfigModel model)
 {
     return(this.SaveConfigAsync(model));
 }
示例#12
0
 public EmailSender(EmailConfigModel emailConfig)
 {
     _configuration = new ConfigurationBuilder()
                      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .Build();
 }
示例#13
0
        private static MailMessage PrepareMailMessage(string subject, string body, IEnumerable <string> to, IEnumerable <string> cc, IEnumerable <string> bcc, IEnumerable <Attachment> attachments, EmailConfigModel emailConfiguration)
        {
            var message     = new MailMessage();
            var fromAddress = new MailAddress(emailConfiguration.MailFrom);

            message.From = fromAddress;
            if (to != null)
            {
                foreach (var item in to.Where(item => !string.IsNullOrWhiteSpace(item)))
                {
                    message.To.Add(item);
                }
            }

            if (cc != null)
            {
                foreach (var item in cc.Where(item => !string.IsNullOrWhiteSpace(item)))
                {
                    message.CC.Add(item);
                }
            }
            if (bcc != null)
            {
                foreach (var item in bcc.Where(item => !string.IsNullOrWhiteSpace(item)))
                {
                    message.Bcc.Add(item);
                }
            }

            message.Subject    = subject;
            message.IsBodyHtml = true;
            message.Body       = body;

            if (attachments != null)
            {
                foreach (var attachment in attachments)
                {
                    message.Attachments.Add(attachment);
                }
            }

            return(message);
        }
 public void SetUp()
 {
     _configModel  = EmailConfigBuilder.Build();
     _emailService = new EmailService(_configModel);
 }
 public EmailService(EmailConfigModel emailConfigModel)
 {
     _emailConfigModel = emailConfigModel;
 }