internal async Task SendEmail(MailingModel request)
        {
            try
            {
                string emailToAddress = request.EmailTo;
                string body           = hostUrl + "/api/Mail?Token=" + Token;

                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(emailFromAddress);
                    mail.To.Add(emailToAddress);
                    mail.Subject    = subject;
                    mail.Body       = body;
                    mail.IsBodyHtml = true;
                    //mail.Attachments.Add(new Attachment("D:\\TestFile.txt"));//--Uncomment this to send any attachment
                    using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                    {
                        smtp.Credentials = new NetworkCredential(emailFromAddress, password);
                        smtp.EnableSsl   = enableSSL;
                        smtp.Send(mail);
                    }
                }
            }
            catch (Exception e)
            {
                messageCollection.addMessage(new Message()
                {
                    Context      = "Exception",
                    ErrorCode    = 1,
                    ErrorMessage = "An Exception Occured during processing: " + e.Message,
                    isError      = true,
                    LogType      = Enums.LogType.Exception
                });
            }
        }
예제 #2
0
        public ActionResult Mailing()
        {
            var model = new MailingModel();

            var d = _ctx.DUserProfiles
                    .Where(x => x.UserName != WebSecurity.CurrentUserName)
                    .Select(x => x.UserName);

            model.Users.AddRange(d);
            return(View(model));
        }
예제 #3
0
        public MailingModel CreateMailing(int batchId, string address, string returnAddress, Format format, IDictionary <string, string> data = null)
        {
            MailingModel mailing = new MailingModel()
            {
                Batch_Id      = batchId,
                Address       = address,
                ReturnAddress = returnAddress,
                Format        = format,
                Data          = data
            };

            return(CreateMailing(mailing));
        }
예제 #4
0
        public void TestGetMailingSuccessful()
        {
            IAuthorizationStrategy basicAuthStrategy   = MockAuthStrategy();
            IServiceCommunicator   serviceCommunicator = MockServiceCommunicator();
            IStamprApiClient       stamprApiClient     = new StamprApiClient.StamprApiClient(_url, _username, _password, serviceCommunicator, basicAuthStrategy);
            MailingModel           model = stamprApiClient.GetMailings(1348).First();

            Assert.AreEqual(model.Format, Format.none);
            Assert.AreEqual(model.Address, "Add");
            Assert.AreEqual(model.ReturnAddress, "RetAdd");
            Assert.AreEqual(model.Mailing_Id, 1348);
            Assert.AreEqual(model.User_Id, 1);
        }
예제 #5
0
        public MailingModel CreateMailing(MailingModel mailing)
        {
            IDictionary <string, object> propertyValues = mailing.ToPostPropertiesDictionary();
            Uri             relUri         = new Uri(_mailingRelatedUri, UriKind.Relative);
            Uri             uri            = new Uri(_baseUri, relUri);
            ServiceResponse serviceReponse = _serviceCommunicator.PostRequest(uri.ToString(), _authorizationStrategy.GetAuthorizationHeader(), propertyValues);

            if (serviceReponse.StatusCode != HttpStatusCode.OK)
            {
                ThrowCommunicationException(serviceReponse);
            }

            MailingModel resultConfigModel = _mailingModelConvertor.ConvertToModel <MailingModel>(serviceReponse.Response);

            return(resultConfigModel);
        }
        internal void DoSqlAction(MailingModel request)
        {
            Token = Guid.NewGuid().ToString();
            ArrayList Params = new ArrayList()
            {
                request.ID,
                request.EmailTo,
                request.Hours,
                Token,
                false
            };

            SQLHandler sqlHandler = new SQLHandler(Params);

            sqlHandler.ExecuteNonQuery(SqlCache.GetSql("InsertMail"));
        }
        public async Task SendMail(MailingModel request)
        {
            validationHandler.CheckNull(request.EmailTo, "Email Address");
            validationHandler.CheckNull(request.ID.ToString(), "ID");
            validationHandler.CheckNull(request.Hours.ToString(), "Hours");

            if (!messageCollection.isErrorOccured)
            {
                MailingHandler handler = new MailingHandler(messageCollection);
                handler.DoSqlAction(request);

                if (!messageCollection.isErrorOccured)
                {
                    await handler.SendEmail(request);
                }
            }
        }
예제 #8
0
        public ActionResult Send(MailingModel model)
        {
            var db = _ctx.webpages_Membership;

            var owner = Enumerable.FirstOrDefault(db.Where(x => x.UserId == WebSecurity.CurrentUserId));

            if (owner == null)
            {
                return(RedirectToAction("Mailing"));
            }

            using (var mail = new MailMessage())
            {
                mail.From = new MailAddress(owner.Email);
                foreach (var name in model.SelectedUsers)
                {
                    var uid = WebSecurity.GetUserId(name);
                    var ms  = Enumerable.FirstOrDefault(db.Where(x => x.UserId == uid));
                    if (ms != null)
                    {
                        mail.To.Add(new MailAddress(ms.Email));
                    }
                }
                mail.Subject    = model.Subject;
                mail.Body       = model.MsgBody;
                mail.IsBodyHtml = true;

                var smtpClient = new SmtpClient()
                {
                    Host                  = WebConfigurationManager.AppSettings["SmtpHost"],
                    Port                  = Convert.ToInt32(WebConfigurationManager.AppSettings["SmtpHostPort"]),
                    EnableSsl             = Convert.ToBoolean(WebConfigurationManager.AppSettings["SmtpEnableSSL"]),
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = Convert.ToBoolean(WebConfigurationManager.AppSettings["SmtpUseDefaultCredentialas"]),
                    Credentials           = new NetworkCredential()
                    {
                        UserName = WebConfigurationManager.AppSettings["SmtpSenderMail"],
                        Password = WebConfigurationManager.AppSettings["SmtpSenderPswd"]
                    }
                };
                smtpClient.Send(mail);
            }
            return(RedirectToAction("Mailing"));
        }
예제 #9
0
 public JsonResult SendMail(ConnectMailViewModel mailModel)
 {
     if (ModelState.IsValid)
     {
         if (Convert.ToBoolean(ConfigurationManager.AppSettings["EnableMailFeature"]))
         {
             MailingModel mailingModel = new MailingModel();
             mailingModel.MailSubject = "Quick Connect Mail";
             mailingModel.MailBody    = PopulateBody(mailModel);
             mailingModel.MailTo      = ConfigurationManager.AppSettings["EmailTo"];
             MailHelper mailHelper = new MailHelper();
             mailHelper.SendMail(mailingModel);
         }
         return(Json(new { Status = "Success", Message = "Message Sent Successfully !!" }));
     }
     else
     {
         return(Json(new { Status = "Error", Message = "Message Sending Failed. Please try again Later!!" }));
     }
 }
예제 #10
0
        public bool SendMail(MailingModel mailing)
        {
            try
            {
                List <string> Tos = mailing.MailTo.Split(',').ToList();

                //
                var body    = mailing.MailBody;
                var message = new MailMessage();
                foreach (string to in Tos)
                {
                    message.To.Add(new MailAddress(to));
                }

                message.From       = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["EmailFrom"]); // replace with valid value
                message.Subject    = mailing.MailSubject;
                message.Body       = string.Format(body);
                message.IsBodyHtml = true;

                using (var smtp = new SmtpClient())
                {
                    var credential = new NetworkCredential
                    {
                        UserName = System.Configuration.ConfigurationManager.AppSettings["EmailUserName"],
                        Password = System.Configuration.ConfigurationManager.AppSettings["EmailPassword"]
                    };
                    smtp.Credentials = credential;
                    smtp.Host        = System.Configuration.ConfigurationManager.AppSettings["EmailSMTPHost"];
                    smtp.Port        = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["EmailSMTPPort"]);
                    smtp.EnableSsl   = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["SSLEnable"]);
                    smtp.Send(message);
                }
                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #11
0
        public void TestPostMailing()
        {
            IAuthorizationStrategy basicAuthStrategy   = MockAuthStrategy();
            IServiceCommunicator   serviceCommunicator = MockServiceCommunicator();
            IStamprApiClient       stamprApiClient     = new StamprApiClient.StamprApiClient(_url, _username, _password, serviceCommunicator, basicAuthStrategy);
            MailingModel           postModel           = new MailingModel()
            {
                Batch_Id      = 4769,
                Format        = Format.none,
                Address       = "Add",
                ReturnAddress = "RetAdd"
            };

            MailingModel model = stamprApiClient.CreateMailing(postModel);

            Assert.AreEqual(model.Batch_Id, postModel.Batch_Id);
            Assert.AreEqual(model.Format, postModel.Format);
            Assert.AreEqual(model.Address, postModel.Address);
            Assert.AreEqual(model.ReturnAddress, postModel.ReturnAddress);
            Assert.Greater(model.Mailing_Id, 0);
            Assert.Greater(model.User_Id, 0);
        }
예제 #12
0
        public IActionResult Contact(MailingModel form)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("plable.homepage", "Homepage@localhost"));
            message.To.Add(new MailboxAddress("plable.contact", "*****@*****.**"));
            message.Subject = "Plable Homepage - Contact";
            message.Body    = new TextPart("plain")
            {
                Text = String.Format("NAME: {0}{3}{3}E-MAIL: {1}{3}{3}MESSAGE: {2}{3}{3}", form.Name, form.Email, form.Text, Environment.NewLine)
            };

            using (var client = new SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect("127.0.0.1", 25, false);
                client.Send(message);
                client.Disconnect(true);
            }

            return(View());
        }
        public async Task <JsonResult> Post([FromBody] MailingModel Request)
        {
            try
            {
                MailingProcessor processor = new MailingProcessor(messageCollection);
                await processor.SendMail(Request);

                if (messageCollection.isErrorOccured)
                {
                    foreach (var message in messageCollection.Messages)
                    {
                        if (message.isError)
                        {
                            Response.StatusCode = 400;
                            return(new JsonResult(message));
                        }
                        else
                        {
                            Response.StatusCode = 500;
                            return(new JsonResult("Internal Server Error"));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                return(new JsonResult(new Message()
                {
                    Context = "Exception",
                    ErrorCode = 1,
                    ErrorMessage = "An Exception Occured during processing: " + e.Message,
                    isError = true,
                    LogType = Enums.LogType.Exception
                }));
            }
            return(new JsonResult("Success"));
        }
예제 #14
0
        public async Task <bool> Send()
        {
            SmtpClient client = new SmtpClient("mysmtpserver")
            {
                UseDefaultCredentials = false,
                //Credentials = new NetworkCredential("oyakmenkul\tssbilgilendirme", "12qwasZX."),
                Host = "srvexc.oyakyatirim.pvt",
                Port = 25,
                //EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Timeout        = 10000
            };



            var reports   = _mailSenderRepository.GetReportEmails();
            var contracts = _mailSenderRepository.GetAllContracts();
            var models    = new List <MailingModel>();

            foreach (var report in reports)
            {
                var contract = contracts.Where(c => c.Id == report.ContractId).FirstOrDefault();
                var model    = new MailingModel()
                {
                    Name  = report.MemberName,
                    Email = report.MemberEmail,
                    Guid  = contract.Guid
                };
                models.Add(model);
            }



            int i = 0;

            //foreach (var item in models.Where(m => m.Email.Contains("*****@*****.**")))
            foreach (var item in models.Where(m => m.Email.Contains("*****@*****.**")))
            {
                i++;

                MailMessage mailMessage = new MailMessage
                {
                    From = new MailAddress("*****@*****.**"),
                    Body =
                        $"<html><head></head><body>" +
                        "<div>" +
                        $"<h4>Sn.{item.Name} </h4>" +
                        "Tamamlayıcı Sağlık Sigortası Anketine katılımınız için teşekkür ederiz.<br>" +
                        "Anket sonuçlarına göre siz değerli üyelerimiz için primlerde revizeler yapılmıştır.<br>" +
                        "Avantajlı güncel primler ile poliçenizi tanzim ettirmek için aşağıdaki linkini tıklayınız!<br>" +
                        "https://test.oyakgrupsigorta.com/ContractMember/" + $"{item.Guid}<br><br>" +
                        "Saygılarımızla,<br>" +
                        "OYAK Grup Sigorta ve Reasürans Brokerliği A.Ş.<br>" +
                        "<br>" +
                        "</div>" +
                        "</body></html>",
                    Subject      = "Tamamlayıcı Sağlık Sigortası Ön Talep Toplama Anketi hk.",
                    IsBodyHtml   = true,
                    Priority     = MailPriority.High,
                    BodyEncoding = Encoding.Default
                };

                try
                {
                    mailMessage.To.Clear();
                    //mailMessage.To.Add(item.Email);
                    //client.Send(mailMessage);
                    mailMessage.To.Add("*****@*****.**");
                    //mailMessage.To.Add("*****@*****.**");
                    client.Send(mailMessage);
                    _logger.LogInformation("Mail Send to {address}", item.Email);
                    Console.WriteLine($"{i} Mail Send to {item.Email}");
                }
                catch (Exception ex)
                {
                    _logger.LogError("Mail Could not be Send to {address} {exception}", item, ex.Message);
                    Console.WriteLine($"Mail Could not be Send to {item.Email} {ex.Message}");
                }
                Thread.Sleep(200);
            }
            return(true);
        }
예제 #15
0
        public virtual ActionResult SendMails(MailingModel mm)
        {
            // Security check
            if (!System.Web.HttpContext.Current.UserIsCrmAdmin())
            {
                alerts.Add("Nisi pooblaščen za CRM.", AlertType.Danger, true);
                return Redirect("~/");
            }

            if (mm.ToEmails == null) mm.ToEmails = "";
            if (mm.NotToEmails == null) mm.NotToEmails = "";

            // cleanup errored emails
            {
                var correctEmails = "";
                var emailErrors = "";
                var emails = mm.ToEmails.Split(" ,;\n".ToCharArray()).Where(x => !string.IsNullOrEmpty(x));
                foreach (var email in emails)
                {
                    if (EmailUtilities.IsValidEmail(email))
                    {
                        correctEmails += email + " ";
                    }
                    else
                    {
                        emailErrors += string.Format("<li>{0}</li>", email);
                    }
                }
                if (emailErrors.NotEmpty())
                {
                    DependencyResolver.Current.GetService<AlertsProvider>().Add(string.Format("Naslednji emajli so napačni in ne bodo odposlani: <ul>{0}</ul>", emailErrors), AlertType.Danger, true);
                }
                mm.ToEmails = correctEmails;
            }

            if (!mm.SendTest)
            {
                // check if model is valid only before sending real emails

                // HACK: instead of using Model.IsValid, which always fails because SupportedLanguage and TagListModel model binders don't get calles,
                // count messages that actually containt some text (type conversion messages don't)
                var validatioErrors =
                    ModelState.Where(x => x.Value.Errors.Any() && !string.IsNullOrEmpty(x.Value.Errors[0].ErrorMessage) && x.Key != "ToEmails" && x.Key != "NotToEmails")
                              .Select(x => x.Value.Errors)
                              .ToList();
                if (validatioErrors.Any())
                {
                    ensureMailingModelDefaults(ref mm);
                    return View("WriteMail", mm);
                }
            }

            //// re-route all links
            //if (!string.IsNullOrWhiteSpace(mm.Body))
            //{
            //    mm.Body = rerouteLinks(mm);
            //}

            string template = createTemplateBody(mm);
            template = _mailSendingUtils.ProcessMailReplaces(template);

            Job job = createJob(mm, template);

            if (mm.SendTest)
            {
                sentTestEmail(mm, job);
            }
            else
            {
                sendEmails(mm, job);
            }

            service.SubmitJob(job);

            ensureMailingModelDefaults(ref mm);

            if (mm.SendTest)
            {
                mm.SendTest = false;
                return View("WriteMail", mm);
            }
            return Redirect("~/Mailing/");
        }
예제 #16
0
        public virtual ActionResult WriteMail(MailingModel mm = null)
        {
            // Security check
            if (!System.Web.HttpContext.Current.UserIsCrmAdmin())
            {
                alerts.Add(new Alert("Nisi pooblaščen za CRM.", AlertType.Danger, true));
                return Redirect("~/");
            }

            if (mm == null)
            {
                mm = new MailingModel();
            }

            ensureMailingModelDefaults(ref mm);

            mm.Images = getImagesForMail(mm.ImageRepository);
            return View(mm);
        }
예제 #17
0
 public virtual ActionResult CopyToNewEmail(MailingModel mm)
 {
     return WriteMail(mm);
 }
예제 #18
0
        private void sentTestEmail(MailingModel mm, Job job)
        {
            string userEmail = _userService.CurrentUserEmail();

            JobEmail mail = new JobEmail()
            {
                Body = _mailSendingUtils.ProcessMailReplaces(mm.Body),
                Guid = Guid.NewGuid(),
                ToAddress = userEmail,
                ToName = System.Web.HttpContext.Current.UserName(),
                Subject = job.Subject + " - (TEST)"
            };
            alerts.Add(new Alert("Testni email poslan na " + userEmail, AlertType.Info, true));
            job.JobEmails.Add(mail);
            mm.TestSent = true;
        }
예제 #19
0
        private void sendEmails(MailingModel mm, Job job)
        {
            int cnt = 0;
            int skippedCnt = 0;

            var mailsToSend = mm.ToEmails.Split(",;\n ".ToCharArray()).Where(m => !m.IsNullOrWhiteSpace()).Distinct();
            foreach (var email in mailsToSend)
            {
                string mailaddress = email.Trim();
                if (mm.NotToEmails != null && mm.NotToEmails.Contains(mailaddress))
                {
                    skippedCnt++; continue;
                }
                if (!string.IsNullOrEmpty(mailaddress) && EmailUtilities.IsValidEmail(mailaddress))
                {
                    JobEmail mail = new JobEmail()
                    {
                        Body = _mailSendingUtils.ProcessMailReplaces(mm.Body),
                        Guid = Guid.NewGuid(),
                        ToAddress = mailaddress,
                        ToName = mailaddress
                    };
                    job.JobEmails.Add(mail);
                    cnt++;
                }
            }
            alerts.Add(
                new Alert(
                    "Poslanih je " + cnt.ToString() + " emailov. " +
                    (skippedCnt > 0 ? skippedCnt.ToString() + " jih mailov je bilo izvzetih." : ""), AlertType.Info,
                    true));
        }
예제 #20
0
        private void ensureMailingModelDefaults(ref MailingModel mm)
        {
            if (mm.Subject == null) mm.Subject = ConfigurationManager.AppSettings["MailingSubjectPrefix"];
            if (mm.Languages == null) mm.Language = settingsProvider.Settings.SiteLanguage.ToString();
            if (mm.ImageRepository == null) mm.ImageRepository = "mails/mailing-" + DateTime.Now.ToString("yyyy-MM");
            if (mm.Languages == null) mm.Languages = settingsProvider.Settings.SupportedLanguages;
            if (mm.MailAccounts == null) mm.MailAccounts = mailAccountsService.GetMailAccounts();

            if (mm.Templates == null)
                mm.Templates =
                    (articleService.AllArticles()
                                   .Where(
                                       a =>
                                       a.Code.StartsWith("mailtemplate", StringComparison.InvariantCultureIgnoreCase))).
                                       Select(a => a.Code).
                                       Distinct().
                                       ToArray();

            if (string.IsNullOrEmpty(mm.Template) && mm.Templates.Any())
                mm.Template = mm.Templates[0];

            initializeAdremas(mm);
        }
예제 #21
0
 private string createTemplateBody(MailingModel mm)
 {
     string template;
     template = "[BODY]";
     var templateArticle = articleService.GetByCode(mm.Template ?? "mailtemplate", mm.Language.ToLanguage());
     if (templateArticle != null && !string.IsNullOrEmpty(templateArticle.Body)) template = templateArticle.Body;
     return template;
 }
예제 #22
0
        private Job createJob(MailingModel mm, string template)
        {
            List<string> fromAddress = new List<string>();
            List<string> fromName = new List<string>();
            List<string> fromLogin = new List<string>();
            List<string> fromPassword = new List<string>();

            foreach (var address in mm.FromAddress.Where(a => !string.IsNullOrEmpty(a)))
            {
                fromAddress.Add(address);
                fromName.Add(mailAccountsService.GetMailAccounts().Where(a => a.Address.Equals(address, StringComparison.InvariantCultureIgnoreCase)).Select(a => a.Name).Single());
                fromLogin.Add(mailAccountsService.GetMailAccounts().Where(a => a.Address.Equals(address, StringComparison.InvariantCultureIgnoreCase)).Select(a => a.Account).Single());
                fromPassword.Add(mailAccountsService.GetMailAccounts().Where(a => a.Address.Equals(address, StringComparison.InvariantCultureIgnoreCase)).Select(a => a.Password).Single());
            }

            Job job;
            job = new Job()
            {
                TemplateText = template,
                FromAddress = string.Join(";", fromAddress),
                FromName = string.Join(";", fromName),
                FromLogin = string.Join(";", fromLogin),
                FromPassword = string.Join(";", fromPassword),
                Guid = Guid.NewGuid(),
                Entered = DateTime.Now,
                IsHtml = true,
                Subject = mm.Subject,
                ReplyToAddress = mm.ReplayToAddress,
                ReplyToName = mm.ReplayToName,
                StartOn = mm.StartSending ?? DateTime.Now,
                EndBy = mm.StopSending ?? (mm.StartSending ?? DateTime.Now).AddHours(6),
                ToPort = 587,
                ToHost = "smtp.gmail.com",
                SenderApp = settingsProvider.Settings.SiteName,
                SenderUser = System.Web.HttpContext.Current.UserName(),
                Body = mm.Body,
                Campaign = mm.Campaign
            };
            job.KeyValuePairs.Add(new JobKeyValuePair()
            {
                Key = "HOME",
                Value = home()
            });
            return job;
        }