// POST: api/Email
        public IHttpActionResult Post(EmailRequest emailRequest)
        {
            try
            {
                //Build the request model for the service to send the email
                PigeonRequest  pigeonRequest  = EmailFactory.CreatePigeonRequest(emailRequest);
                PigeonResponse pigeonResponse = _emailProvider.SendAFitPigeon(pigeonRequest);

                if (pigeonResponse.Success)
                {
                    //Create the Api response for the successful post request
                    EmailResponse emailResponse = EmailFactory.CreateEmailResponse(pigeonResponse);

                    //Save to database if the email is sent successfully
                    _emailSavingService = new EmailSavingService(_commonProvider, _databaseRepoProvider,
                                                                 emailRequest, emailResponse);

                    //request = CommonUtility.SerializeObject(emailRequest);
                    //response = CommonUtility.SerializeObject(emailResponse);
                    //var isSaved = databaseStuff.SaveaSomethingAwesome(request, response, 1, 2);

                    return(Ok(emailResponse));
                }
                else
                {
                    return(BadRequest("Response was not a success: " + pigeonResponse.Message));
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Example #2
0
File: Email.cs Project: ncelsRS/ptp
 public Email(BaseNotify notify)
 {
     ToEmail = notify.Email;
     Message = EmailFactory.RenderViewToString(notify.ToString(), notify);
     Subject = notify.Subject;
     //  Send = notify.Send;
 }
Example #3
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                EmailFactory.SendEmailAsync(new ForgotPassword(user, callbackUrl));
                // await m.SendMessageAsync();

                return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public static void SendWarning(string to, Prescription prescription)
        {
            _emailFactory = new EmailFactory(to);
            var mail = _emailFactory.GetEmailWarning(prescription);

            Service.SendAsync(mail.ToIdentityMessage());
        }
Example #5
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        public static void SendEmail()
        {
            var emailServiceBusiness = new Business.Services.EmailService.EmailBusiness();

            var email = emailServiceBusiness.GetTodayData();

            var emailFactory = new EmailFactory("*****@*****.**", "*****@*****.**");

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"进来简历总量:{email.ResumeCount}");
            stringBuilder.AppendLine($"投递进来简历量:{email.DeliverCount}");
            stringBuilder.AppendLine($"Cookie 进来简历量:{email.ResumeCount - email.DeliverCount}");
            stringBuilder.AppendLine($"无Json源简历量:{email.NoJsonCount }");
            stringBuilder.AppendLine($"上传简历量:{email.UploadCount}");
            stringBuilder.AppendLine($"简历新增量:{email.CreateCount}");
            stringBuilder.AppendLine($"简历更新量:{email.UpdateCount}");
            stringBuilder.AppendLine($"简历剩余量:{email.SurplusCount}");
            stringBuilder.AppendLine($"本周平均新增量:{email.AvgCreateCount}");

            emailFactory.Body = stringBuilder.ToString();

            emailFactory.IsBodyHtml = false;

            emailFactory.Subject = $"{DateTime.Now.AddDays(-1):yyyy-MM-dd} 每日数据指标统计(龙志杰)";

            emailFactory.Send();
        }
Example #6
0
        /// <summary>
        /// Emails the user notice of the application status change
        /// </summary>
        private void EmailStatusChange(int userId, int schemeId, int templateId)
        {
            //get the users email
            var user = PemsEntities.Users.FirstOrDefault(x => x.UserID == userId);

            if (user != null)
            {
                //now get the DiscountSchemeEmailTemplate for this customer and templateID passed in. this will get us the subject and body fo the email
                var dsEmailTemplate = PemsEntities.DiscountSchemeEmailTemplates.FirstOrDefault(x => x.CustomerId == user.DefaultCustomerID && x.EmailTemplateTypeId == templateId);
                if (dsEmailTemplate != null)
                {
                    var    to      = user.UserEmail;
                    var    from    = "*****@*****.**";
                    string subject = dsEmailTemplate.EmailSubject;
                    var    body    = dsEmailTemplate.EmailText;
                    //now lets get the "from". get the DSCustomerInfo for this templateID , customerid and scheme id
                    var dsCustomerInfo =
                        PemsEntities.DiscountSchemeCustomerInfoes.FirstOrDefault(
                            x => x.CustomerId == user.DefaultCustomerID &&
                            x.DiscountSchemeEmailTemplateId == dsEmailTemplate.DiscountSchemeEmailTemplateId &&
                            x.DiscountSchemeId == schemeId);
                    if (dsCustomerInfo != null)
                    {
                        from = dsCustomerInfo.FromEmailAddress;
                    }

                    //send email to user
                    var mailer = new EmailFactory();
                    mailer.UserSchemeStatus(to, from, subject, body, "EmailStatusChange").Send();
                }
            }
        }
Example #7
0
        public static INotifier Create(NotifierType type, ILogger logger, IConfigurationSection section)
        {
            NotifierFactory factory;

            switch (type)
            {
            case NotifierType.Pushbullet:
                factory = new PushbulletFactory();
                break;

            case NotifierType.Webhook:
                factory = new WebhookFactory();
                break;

            case NotifierType.Email:
                factory = new EmailFactory();
                break;

            case NotifierType.Telegram:
                factory = new TelegramFactory();
                break;

            default:
                throw new NotImplementedException(type.ToString());
            }

            INotifier notifier = factory.Create(logger, section);

            notifier.Cameras = section.GetSection("Cameras").Get <List <string> >();

            return(notifier);
        }
Example #8
0
        public void CanSendEmail()
        {
            var queueStreamName  = "Test" + EventStoreQueueConstants.QueueStreamName;
            var outboxStreamName = "Test" + EventStoreQueueConstants.OutboxStreamName;

            var mainLog = LogManager.GetLoggerFor("TEST");

            // EventStoreSettings
            var eventStoreIp      = "127.0.0.1";
            var eventStoreTcpPort = 1113;
            var eventStoreUser    = "******";
            var eventStorePass    = "******";

            // Conectando el EventStore
            var eventStoreSettings = ConnectionSettings
                                     .Create()
                                     .KeepReconnecting()
                                     .SetHeartbeatTimeout(TimeSpan.FromSeconds(30))
                                     .SetDefaultUserCredentials(new UserCredentials(eventStoreUser, eventStorePass))
                                     .Build();

            var tcp              = new IPEndPoint(IPAddress.Parse(eventStoreIp), eventStoreTcpPort);
            var connection       = EventStoreConnection.Create(eventStoreSettings, tcp);
            var connectionSource = "local";

            connection.Closed += (s, e) =>
                                 mainLog.Error($"The {connectionSource} ES connection was closed");
            connection.Connected += (s, e) =>
                                    mainLog.Log($"The connection with {connectionSource} ES was establised");
            connection.Disconnected += (s, e) =>
                                       mainLog.Log($"The connection with {connectionSource} ES was lost");
            connection.Reconnecting += (s, e) =>
                                       mainLog.Log($"Reconnecting with {connectionSource} ES");
            connection.ConnectAsync().Wait();

            var serializer = new JsonSerializer();

            var repo = new EventSourcedRepository(connection, serializer, enablePersistentSnapshotting: true, snapshotInterval: 1);

            var client = new SimpleEmailSenderEsClient(connection, serializer, queueStreamName);

            var mail = EmailFactory.NewFrom("Alexis", "*****@*****.**")
                       .To("Alexis", "*****@*****.**")
                       .Subject("Test")
                       .BodyUsingTemplateFromFile(@"~/testmail.html", new { Name = "Chary" })
                       .Build();

            client.Send(mail);

            // Consuming
            //var sender = new FakeEmailSender("mail.fecoprod.com.py", 25);
            var sender = new WaitEmailSender("mail.fecoprod.com.py", 25);

            using (var job = new MailSendingJob(connection, repo, serializer, sender, queueStreamName, outboxStreamName))
            {
                job.Start();

                sender.WaitForSending();
            }
        }
Example #9
0
        public ActionResult Startup(RegisterViewModel model)
        {
            if (UserManager.Users.Any())
            {
                return(RedirectToAction("Index"));
            }
            if (ModelState.IsValid)
            {
                var user = new Models.ApplicationUser
                {
                    UserName         = model.Email,
                    Email            = model.Email,
                    PhoneNumber      = model.Phone,
                    RegisterName     = model.Name,
                    Registered       = DateTime.UtcNow,
                    IsAcceptedOffert = true
                };
                var result = UserManager.Create(user, model.Password);
                if (result.Succeeded)
                {
                    try
                    {
                        var userinfo = new UserInfo()
                        {
                            User            = user,
                            Name            = model.Name ?? model.Email,
                            AdditionalMail  = "",
                            AdditionalPhone = "",
                            Patronymyc      = "",
                            Surname         = ""
                        };
                        db.Insert(userinfo, User.Identity.GetUserId());
                        //  var b = RolesManager.Roles.ToList();
                        UserManager.AddToRole(user.Id, "root");
                        user.Registered       = DateTime.UtcNow;
                        user.AllowPromoEmails = true;
                        user.AllowTradeEmails = true;
                        user.EmailConfirmed   = true;
                        user.AllowedIp        = model.Ip;
                        user.IsDebug          = true;
                        UserManager.Update(user);

                        user.IsAcceptedOffert = true;
                        UserManager.Update(user);
                        db.SaveChanges();
                        //Mailer.SendMail(user.Email, "Для подтверждения е-мэйла перейдите по <a href=\"" + callbackUrl + "\">ccылке</a>");
                        //  Mailer.SendRegistrationMail(user.RegisterName ?? model.Name, user.Email, callbackUrl);
                        EmailFactory.SendEmailAsync(new SuccessRegister(user, "")); // {Link = callbackUrl};
                        //await m.SendMessageAsync();
                        //await EmailFactory.SendEmailAsync(new Email(m));
                    }
                    catch (Exception ex)
                    {
                        return(View("Error"));
                    }
                }
            }
            return(View());
        }
Example #10
0
        private bool sendForgotPasswordEmail(ApplicationUser user, string code)
        {
            try
            {
                string baseUrl = Request.Url.Authority;
                // For dev
                if (Request.Url.Authority.Contains("localhost"))
                {
                    baseUrl = "http://vps232338.ovh.net";
                }

                string callbackUrl = baseUrl + "/Angular/index.html#change_password" + "?userid=" + user.Id + "&code=" + code;

                EmailFactory factory = new EmailFactory();
                MailMessage  message = new MailMessage();
                message.To.Add(new MailAddress(user.Email));
                message.IsBodyHtml = true;
                if (HostingEnvironment.MapPath("~/Angular/email_templates/email_forgot_password.html") != null)
                {
                    message.Body = System.IO.File.ReadAllText(HostingEnvironment.MapPath("~/Angular/email_templates/email_forgot_password.html"));
                }
                //Dev mode
                else
                {
                    message.Body = System.IO.File.ReadAllText(@"D:\Travail\Reta\RetaTrunk\Reta\Reta\Angular\email_templates\email_forgot_password.html");
                }

                // embed logo if exist
                string path = getPathToLogoForUser(user);
                if (!string.IsNullOrEmpty(path))
                {
                    Attachment inlineLogo = new Attachment(path);
                    message.Attachments.Add(inlineLogo);
                    string contentID = "Logo";
                    inlineLogo.ContentId = contentID;
                    //To make the image display as inline and not as attachment
                    inlineLogo.ContentDisposition.Inline          = true;
                    inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                    string urlToTemplateFile = "cid:" + contentID;
                    message.Body = message.Body.Replace("##urlToTemplateFolder##", urlToTemplateFile);
                }
                else
                {
                    message.Body = message.Body.Replace("##urlToTemplateFolder##", "");
                }

                message.Body    = message.Body.Replace("##urlToConfirmPage##", callbackUrl);
                message.Subject = "Forgot Password";
                message.From    = new MailAddress(ConfigurationManager.AppSettings["ForgotPassword:Email:DefaultFrom"]);
                factory.Send(message);
                logger.Info("Forgot password sent to : " + user.Email);
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return(false);
            }
        }
Example #11
0
        public void Upgrade()
        {
            List <string> msg = new List <string>();

            email = EmailFactory.EmailFact("emailType");
            Console.WriteLine(email.SendEmail());
            Console.WriteLine("membership updated");
        }
Example #12
0
        public void Active()
        {
            List <string> msg = new List <string>();

            email = EmailFactory.EmailFact("emailType");
            Console.WriteLine(email.SendEmail());
            Console.WriteLine("Activating user");
        }
Example #13
0
        public async Task <ActionResult> Create(NewAuctionViewModel model)
        {
            model.IsOffer = false;
            model.IsOrder = true;
            // model.SelectedProduct = model?.ProductsList?.FirstOrDefault(c => c.Code == TradeTypes.closeFixed.ToString())??new Areas.Admin.Models.CatalogModel() { Code= "closeFixed" };
            try
            {
                if ((model.TradeEnd - model.TradeBegin).TotalMinutes < 59)
                {
                    return
                        (Json(
                             new
                    {
                        Success = false,
                        responseText =
                            LocalText.Inst.Get("error", "Orders.Create.WrongTimeOfOffer",
                                               "Час актуальності пропозиції повинен бути не меншим за годину",
                                               "Время актуальности предложения должно быть, как минимум, равным часу")
                    },
                             JsonRequestBehavior.AllowGet));
                }
                model.HasRedemptionPrice = true;
                model.IsPreApproved      = true;
                model.IsAccepted         = true;
                model.RedemptionPrice    = model.StartPrice;

                var trade = tradeDataLayer.CreateTrade(model, User.Identity.GetUserId());
                trade.BankBill = Db.BankBills.FirstOrDefault(c => c.Id == trade.BankBillId);
                //  var trademodel = tradeDataLayer.CreateTradeViewModel(trade);
                foreach (var user in UserManager.Users)
                {
                    EmailFactory.SendEmailAsync(new NewOrder(user, tradeDataLayer.CreateTradeViewModel(trade, user)));
                }

                await EmailFactory.Brodcast(new Broadcast()
                {
                    Body = "Нова заявка", Subject = "На РТР створено нову пропозицію. Подивіться, може у вас є що запропонувати?"
                });

                //Mailer.SendMail("*****@*****.**", "Новый торг на модерации",
                //    "Уважаемый модератор, просьба одобрить новый торг: " + Url.Action("TradesOnApproving", "Trade", null, Request.Url.Scheme));
                return(Json(new { Success = true, redirectUrl = Url.Action("Index", "Orders") },
                            JsonRequestBehavior.AllowGet));
            }
            catch (ArgumentNullException ex)
            {
                logger.Error(ex);
                return(Json(new { Success = false, responseText = LocalText.Inst.Get("error", "errorfilenotuploaded", "Паспорт товару не загружено, перейдіть на сторінку модерації торгів та спробуйте знову") }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(Json(new { Success = false, responseText = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #14
0
        private void BindGrid(int currentPage)
        {
            try
            {
                SisPackController.AdministrarGrillas.Configurar(this.dtgEmails, "EmailID", this.CantidadOpciones);

                if (Session["dsEmails"] == null)
                {
                    IEmail emails = EmailFactory.GetEmail();
                    emails.TipoAvisoID = this.ddlTipoAvisoConsul.SelectedValue.Trim().Equals("")?0:Convert.ToInt32(this.ddlTipoAvisoConsul.SelectedValue.Trim());
                    this.dsEmails      = emails.GetEmailDataSet();
                    emails             = null;
                }
                else
                {
                    this.dsEmails = (DsEmail)Session["dsEmails"];
                    if (this.dtgEmails.EditItemIndex != -1)
                    {
                        /* Si se desea editar o agregar un registro. */
                        DataGridItem     item = this.dtgEmails.Items[this.dtgEmails.EditItemIndex];
                        DsEmail.DatosRow dr   = (DsEmail.DatosRow) this.dsEmails.Datos.Rows[item.DataSetIndex];

                        TextBox emailID = (TextBox)item.FindControl("txtEmailID");
                        dr.EmailID = Convert.ToInt32(emailID.Text.Trim());

                        TextBox denominacion = (TextBox)item.FindControl("txtDenominacion");
                        dr.Denominacion = denominacion.Text.Trim();

                        TextBox direccion = (TextBox)item.FindControl("txtDireccion");
                        dr.Direccion = direccion.Text.Trim();

                        DropDownList tipoAviso = (DropDownList)item.FindControl("ddlTipoAviso");
                        string       selValue  = tipoAviso.SelectedValue;
                        dr.TipoAvisoID = selValue == "" ? 0 : Convert.ToInt32(selValue);

                        item         = null;
                        dr           = null;
                        emailID      = null;
                        denominacion = null;
                        direccion    = null;
                        tipoAviso    = null;
                    }
                }

                Session["dsEmails"]             = this.dsEmails;
                this.dtgEmails.DataSource       = this.dsEmails;
                this.dtgEmails.CurrentPageIndex = currentPage;
                this.dtgEmails.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #15
0
        public async Task <ActionResult> Order(UserOrderViewModel model)
        {
            try
            {
                var offer = Db.Trades.Find(model.OfferId);
                if (offer == null)
                {
                    logger.Info("Какой-то чмошник что-то чудит");
                    throw new ArgumentNullException("lot", "Bet must not be empty");
                }
                var user = UserManager.FindById(User.Identity.GetUserId());

                tradeDataLayer.CheckOfferOnOrder(user, model, offer);
                var order = new Order(model);
                Db.Insert(order, user.Id);
                offer.Buyers.Add(order.Buyer);
                Db.UpdateEntity(offer, user.Id);


                foreach (var u in offer.Orders.GroupBy(c => c.Buyer).SelectMany(f => f.Key.ContragentUsers).ToList())
                {
                    await hub.UpdateTradeTable(offer.Id, u.UserName);
                }
                foreach (var u in offer.Seller.ContragentUsers.ToList())
                {
                    await hub.UpdateTradeTable(offer.Id, u.UserName);

                    EmailFactory.SendEmailAsync(new NewReplyToOffer(u, order));
                }

                return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
            }
            catch (ArgumentOutOfRangeException ex)
            {
                logger.Error(ex);
                return
                    (Json(new
                {
                    success = false,
                    error = $"{LocalText.Inst.Get("error", "VolumeTooMuch", "Зменшіть об’єм Вашої заявки", "Уменьшите объем Вашей заявки")} {GetFullErrorMessage(ex)}"
                }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return
                    (Json(new
                {
                    success = false,
                    error = $"{LocalText.Inst.Get("error", "errorBet", "Відбулася помилка", "Произошла ошибка")} {GetFullErrorMessage(ex)}"
                }, JsonRequestBehavior.AllowGet));
            }
        }
Example #16
0
        public async Task <IEnumerable <Email> > CreateEmailsAsync(EmailTemplate template)
        {
            Guard.Against.Null(template, nameof(template));
            Guard.Against.NullOrEmpty(template.Type, nameof(template.Type));
            Guard.Against.NullOrEmpty(template.Content.Subject, nameof(template.Content.Subject));
            Guard.Against.NullOrEmpty(template.Content.Text, nameof(template.Content.Text));

            var emailContext = await _emailContextProvider.GetEmailContextAsync();

            EmailFactory emailFactory = _emailFactoryProducer.GetEmailFactory(template.Type);

            return(emailFactory.CreateEmails(template.Content, emailContext));
        }
Example #17
0
        public JsonResult EnviarMail(int EvaluacionPromocionID, int EvaluacionMedicionID, bool EsEvaluado)
        {
            //Se obtiene el listado de alumnos para el envío de correo
            List <PromocionMedicionCicloParticipante> listadoParticipantes = DAPromocionMedicionCicloParticipante.Listado(EvaluacionPromocionID, EvaluacionMedicionID);

            string evaluado       = "&idEvaluado=0&Externo=False";
            string link           = string.Empty;
            string rutaCorreo     = EsEvaluado ? "~/Areas/Administrador/Views/Link/EmailExterno.cshtml" : "~/Areas/Administrador/Views/Link/Email.cshtml";
            int    participanteID = 0;
            string msjeExito      = "Se enviaron los correos a cada participante";

            try
            {
                foreach (PromocionMedicionCicloParticipante participante in listadoParticipantes)
                {
                    using (EmailProvider provider = EmailFactory.GetEmailProvider(
                               EmailFactory.Providers.Default,
                               ConfigurationManager.AppSettings["EnvioMailCompromisoAlumno"]))
                    {
                        if (EsEvaluado)
                        {
                            participanteID = (int)DAParticipante.ObtenerParticipante(Convert.ToInt32(ConfigurationManager.AppSettings["IdTipoDocumentoDefault"].ToString()), participante.ParticipanteNroDoc).ParticipanteID;
                            evaluado       = "&idEvaluado=" + participanteID + "&Externo=true";
                        }

                        link = "http://msa.esan.edu.pe/Alumno/Registro/Formulario?idPromocion=" + EvaluacionPromocionID.ToString() +
                               "&idMedicion=" + EvaluacionMedicionID.ToString() + evaluado;
                        ViewBag.LinkEval  = link;
                        ViewBag.LinkVideo = participante.DireccionVideo;

                        provider.AgregarDireccion(TipoDirecciones.To, ConfigurationManager.AppSettings["EsPrueba"] == "1" ? ConfigurationManager.AppSettings["CorreoPrueba"] : participante.ParticipanteNroDoc + ConfigurationManager.AppSettings["DominioCorreoEnvio"]);

                        provider.Enviar(
                            HttpUtility.HtmlDecode(
                                General.RenderPartialViewToString(this,
                                                                  rutaCorreo
                                                                  , ViewBag))
                            , true
                            , System.Net.Mail.MailPriority.Normal);
                    }
                }
            }
            catch
            {
                msjeExito = "A ocurrido un error al enviar el correo.";
            }



            return(Json(new { exito = msjeExito }, JsonRequestBehavior.AllowGet));
        }
Example #18
0
        public void CloseTrade(Trade trade)
        {
            try
            {
                logger.Info($"try close trade {trade.Id}");
                // trade.SendPopups(trade.Buyers.SelectMany(c => c.ContragentUsers).Distinct().ToList(), _notificationHub, NotifyType.AboutTradeEnd);
                foreach (var user in trade.Seller.ContragentUsers.ToList().Distinct())
                {
                    logger.Info($"Send seller letter to {user.Email}");
                    int winnerscount = TradeWinners(trade).Count();
                    EmailFactory.SendEmailAsync(new SellerLetter(user, trade, winnerscount));
                }
                foreach (var buyer in TradeWinners(trade).Distinct())
                {
                    CreateBill(trade.Id, buyer.Id);

                    foreach (var user in GetContragentUsers(buyer).Distinct().ToList())
                    {
                        var bets =
                            buyer.Bets.Where(f => f.TradeId == trade.Id && (f.IsActual || f.IsRedemption))
                            .ToList();
                        #region SendMail to winner
                        logger.Info($"send WINNER leter to {user.Email}");
                        EmailFactory.SendEmailAsync(new WonFix(trade, bets, buyer, user));
                    }
                    #endregion

                    foreach (var loser in TradeLosers(trade.Id).ToList().Distinct().ToList())
                    {
                        EmailFactory.SendEmailAsync(new LoserLetter(loser, trade.Id, trade.Seller.LongName));
                    }

                    foreach (var failedtrade in GetFailedTrades())
                    {
                        logger.Info($"NEED TO SEND LETTERS ABOUT FAILED TRADE: {failedtrade.Id}");
                        failedtrade.IsClosedByBills = true;
                        _context.UpdateEntity(failedtrade);
                    }
                }
                logger.Info($"CLOSING trade {trade.Id}");
                trade.IsClosedByBills = true;
                _context.UpdateEntity(trade);
            }


            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Example #19
0
        public void ParsePasswordRecoveryTemplate()
        {
            const string userName     = "******";
            const string recoveryLink = "X_RECOVERYLINK_X";

            var message = EmailFactory.ParseTemplate(new PasswordRecovery
            {
                UserName     = userName,
                RecoveryLink = recoveryLink
            }, EmailType.PasswordRecovery);

            Assert.That(message.Contains(userName));
            Assert.That(message.Contains(recoveryLink));
        }
Example #20
0
        public async Task <HttpStatusCode> SendEmailHelper(object item, Email datamodel)
        {
            IEmailProvider emailProdvider = EmailFactory.getEmailInstance((EmailEnum)Enum.Parse(typeof(EmailEnum), item.ToString()));

            responseMessage = await emailProdvider.SendEmailAsync(datamodel);

            if (responseMessage.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception(responseData);
            }
            else
            {
                return(HttpStatusCode.OK);
            }
        }
Example #21
0
        protected void dtgEmails_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                /* Obtener los datos de la grilla. */
                this.dsEmails = (DsEmail)Session["dsEmails"];
                /* Posicionarse en el registro deseado. */
                DsEmail.DatosRow dr;
                if (this.dtgEmails.CurrentPageIndex > 0)
                {
                    dr = (DsEmail.DatosRow) this.dsEmails.Datos.Rows[this.dtgEmails.CurrentPageIndex * e.Item.DataSetIndex];
                }
                else
                {
                    dr = (DsEmail.DatosRow) this.dsEmails.Datos.Rows[e.Item.DataSetIndex];
                }

                IEmail email = EmailFactory.GetEmail();
                email.EmailID      = dr.EmailID;
                email.Denominacion = dr.Denominacion;
                email.Direccion    = dr.Direccion;
                email.TipoAvisoID  = dr.TipoAvisoID;

                email.Guardar();
                dr    = null;
                email = null;

                this.dtgEmails.EditItemIndex = -1;
                Session["dsEmails"]          = null;
                this.BindGrid(0);
            }
            catch (Exception ex)
            {
                string mensaje = ex.Message;
                try
                {
                    if (mensaje == "" || mensaje == null)
                    {
                        mensaje = ex.Message;
                    }
                }
                catch (Exception)
                {
                    mensaje = ex.Message;
                }
                ((ErrorWeb)this.phErrores.Controls[0]).setMensaje(mensaje);
            }
        }
Example #22
0
        private static EmailFactory ArrangeEmailFactory()
        {
            var renderer = new Mock <ITemplateRenderer>();
            var sender   = new Mock <ISender>();
            var options  = new Mock <IOptions <MailingSettings> >();

            options.SetupGet(m => m.Value).Returns(new MailingSettings
            {
                FromName    = FromName,
                FromAddress = FromAddress
            });

            var emailFact = new EmailFactory(renderer.Object, sender.Object, options.Object);

            return(emailFact);
        }
        /// <summary>
        /// Send conformation email to customer <paramref name="email"/>
        /// </summary>
        /// <param name="email"></param>
        private void SendConfirmationEmail(string email)
        {
            EmailFactory factory = new EmailFactory();
            MailAddress  to      = factory.GetMailAddress(email);
            MailAddress  from    = factory.GetMailAddress("fromAddress");
            SmtpClient   client  = factory.GetSmtpClient();

            MailMessage message = factory.GetMailMessage(to, from);

            message.Body    = "Thank oyu for booking at us";
            message.Subject = "Thanks for your purchase!";

            EmailSender sender = factory.GetEmailSender(message, client, message.To.First(), message.From);

            sender.SendEmail();
        }
Example #24
0
        public static void Main(string[] args)
        {
            var fromEmail = ConfigurationManager.AppSettings["google_username"];
            var password = ConfigurationManager.AppSettings["google_password"];

            var mail = new MailMessage(fromEmail,"*****@*****.**");
            mail.Subject = "Test email";
            mail.Body =  "Hello, World!";

            var emailCred = EmailFactory.CrateEmailClient(fromEmail,password, EmailClients.Google);

            var email= new Email(emailCred,mail);

            new EmailSenderService().SendEmail(email);
            Console.WriteLine("email sent");
        }
Example #25
0
        public async Task <ActionResult> Edit(ApproveModel model)
        {
            try
            {
                var currentuser = UserManager.FindById(User.Identity.GetUserId());
                var cont        = db.Contragents.Single(x => x.Id == model.ContragentId);
                cont.ApprovingComment    = model.Comment;
                cont.HasContractCopy     = model.HasContractCopy;
                cont.HasContractOriginal = model.HasContractOriginal;
                cont.IsApproved          = model.IsApproved;
                cont.IsBuyer             = model.IsBuyer;
                cont.IsSeller            = model.IsSeller;
                cont.ApprovedByUserId    = currentuser.Id;
                cont.ApprovedByUser      = currentuser;
                cont.ContractOnSignin    = model.ContractIsOnSign;
                db.UpdateEntity(cont, currentuser.Id);

                if (cont.IsApproved)
                {
                    CheckRoles(cont);

                    EmailFactory.SendEmailAsync(new LegalActive(cont.CreatedByUser, cont));
                }
                else
                {
                    CheckRoles(cont);
                    if (model.SendMail)
                    {
                        foreach (var user in cont.ContragentUsers.ToList())
                        {
                            logger.Info($"contragent {cont.LongName} deactivated, sending mail");

                            EmailFactory.SendEmailAsync(new LegalNotActive(user, cont));
                        }
                    }
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                ModelState.AddModelError("", ex.Message);
                return(RedirectToAction("Details", new { @id = model.ContragentId }));
            }
        }
Example #26
0
        protected override void DrawWindow(int windowId)
        {
            using (Helper.HeaderBeginHorizontal(SkinData))
            {
                if (Helper.Button(SkinData, "Close"))
                {
                    Hide();
                }

                GUILayout.FlexibleSpace();

                if (EmailFactory.GetEmailSender(DevelopmentConsole.Instance.EmailLogSupportEnabled).CanSendEmail() && Helper.Button(_skinData, "Email"))
                {
                    var body = $"{_logEntry.LogMessage}\n\n{_logEntry.StackTrace}";

                    var filename = Application.temporaryCachePath + "/log_" + DateTime.Now.ToString("o") + ".txt";
                    var writer   = new StreamWriter(filename);
                    writer.WriteLine(_logEntry.LogMessage);
                    writer.WriteLine(_logEntry.StackTrace);
                    writer.Close();

                    EmailFactory.GetEmailSender(DevelopmentConsole.Instance.EmailLogSupportEnabled).Email(
                        filename,
                        "text/plain",
                        filename,
                        "",
                        "Email Log",
                        body);
                }
            }

            _scrollPosition = GUILayout.BeginScrollView(_scrollPosition);

            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                GUI.enabled = false;
            }

            GUI.color = new UnityEngine.Color(1, 1, 1, 2);
            Helper.TextArea(SkinData, new GUIContent(_logEntry.LogMessage + "\n" + _logEntry.StackTrace), GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true));
            GUI.enabled = true;
            GUILayout.EndScrollView();

            GUI.FocusWindow(windowId);
            GUI.BringWindowToFront(windowId);
        }
Example #27
0
        private void Send(JArray jArray)
        {
            var count = 0;

            foreach (var recipient in jArray)
            {
                var emailFactory = new EmailFactory((string)recipient["email"]);

                var body = (string)recipient["name"];

                var ascii = (int)Convert.ToChar(body.Substring(0, 1).ToLower());

                if (ascii < 97 || ascii > 122)
                {
                    body = body.Substring(0, 1);
                }

                emailFactory.Body = $"{body} {this.tbx_Body.Text}";

                emailFactory.Subject = this.tbx_Subject.Text;

                emailFactory.IsBodyHtml = false;

                if (this.lbl_Annex.Text != "未选择附件...")
                {
                    emailFactory.Attachments(this.lbl_Annex.Text);
                }

                try
                {
                    emailFactory.Send();

                    RunInMainthread(() =>
                    {
                        Program.SetLog(this.tbx_Schedule, $"发送成功!{(string)recipient["email"]} {++count} / {jArray.Count}");
                    });
                }
                catch (Exception ex)
                {
                    RunInMainthread(() =>
                    {
                        Program.SetLog(this.tbx_Schedule, $"发送失败!{ex.Message} {(string)recipient["email"]} {++count} / {jArray.Count}");
                    });
                }
            }
        }
Example #28
0
        protected void dtgEmails_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                string script;
                /* Obtener los datos de la grilla. */
                this.dsEmails = (DsEmail)Session["dsEmails"];
                /* Posicionarse en el registro deseado. */
                DsEmail.DatosRow dr = (DsEmail.DatosRow) this.dsEmails.Datos.Rows[e.Item.DataSetIndex];

                IEmail email = EmailFactory.GetEmail();
                email.EmailID = dr.EmailID;
                if (!email.Eliminar())
                {
                    /** Si se produjo algún error **/
                    script  = "<script language='javascript'>\n";
                    script += "alert('La eliminación no se realizó debido a errores.');\n";
                    script += "</script>";
                    Page.RegisterStartupScript("scriptError", script);
                }
                dr    = null;
                email = null;

                this.dtgEmails.EditItemIndex = -1;
                Session["dsEmails"]          = null;
                this.BindGrid(0);
            }
            catch (Exception ex)
            {
                string mensaje = ex.Message;
                try
                {
                    if (mensaje == "" || mensaje == null)
                    {
                        mensaje = ex.Message;
                    }
                }
                catch (Exception)
                {
                    mensaje = ex.Message;
                }
                ((ErrorWeb)this.phErrores.Controls[0]).setMensaje(mensaje);
            }
        }
Example #29
0
        private static void Main(string[] args)
        {
            /* TODO:
             * 1. Changes from PX and Verity fallout
             */

            var excelFileFactory = new ExcelFileFactory();
            var mailMergeFactory = new MailMergeFactory(excelFileFactory);
            var globalAddressList = GetGlobalAddressList();
            var configurationStorage = new ConfigurationStorage();

            InitializeApplication(configurationStorage, globalAddressList);

            var emailFactory = new EmailFactory(StarFisherContext.Instance, excelFileFactory, mailMergeFactory);
            var memoHelper = new StarAwardsMemoHelper(excelFileFactory, mailMergeFactory);

            var menuItemCommands = new List<IMenuItemCommand>
            {
                new LoadNominationsFromSnapshotMenuItemCommand(StarFisherContext.Instance),
                new LoadNominationsFromSurveyExportMenuItemCommand(StarFisherContext.Instance),
                new FixNomineesMenuItemCommand(StarFisherContext.Instance, globalAddressList),
                new FixNomineeWriteUpsMenuItemCommand(StarFisherContext.Instance),
                new DisqualifyNomineesMenuItemCommand(StarFisherContext.Instance),
                new RemoveNominationMenuItemCommand(StarFisherContext.Instance),
                new CreateHumanResourceNomineeValidationEmailMenuItemCommand(StarFisherContext.Instance, emailFactory),
                new CreateAwardVotingKeyMenuItemCommand(StarFisherContext.Instance, excelFileFactory),
                new CreateAwardVotingGuideMenuItemCommand(StarFisherContext.Instance, mailMergeFactory),
                new CreateVotingSurveyEmailsMenuItemCommand(StarFisherContext.Instance, emailFactory),
                new CreateVotingKeyEmailMenuItemCommand(StarFisherContext.Instance, emailFactory),
                new CreateLuncheonInviteeListEmailMenuItemCommand(StarFisherContext.Instance, emailFactory),
                new SendNominationNotificationEmailsMenuItemCommand(StarFisherContext.Instance, mailMergeFactory),
                new SelectAwardWinnerMenuItemCommand(StarFisherContext.Instance),
                new UnselectAwardWinnerMenuItemCommand(StarFisherContext.Instance),
                new CreateCertificateEmailMenuItemCommand(StarFisherContext.Instance, emailFactory),
                new CreateStarAwardsMemoArtifactsMenuItemCommand(StarFisherContext.Instance, memoHelper),
                new InitializeApplicationMenuItemCommand(StarFisherContext.Instance, globalAddressList,
                    configurationStorage),
                new ExitCommand(StarFisherContext.Instance)
            };

            var topLevelMenu = new TopLevelMenuCommand(StarFisherContext.Instance, menuItemCommands);
            topLevelMenu.Run();
        }
Example #30
0
        /// <summary>
        /// 同步邮件
        /// </summary>
        /// <param name="model"></param>
        /// <param name="number"></param>
        async Task AsyncEmail(EmailManger model, int?number)
        {
            Logger($"邮箱:{model.Email} 正在获取邮件!");
            await UpdateEmailSynchronization(model.Email).ConfigureAwait(false);

            var service = EmailFactory.Service(model, EnumTools.EailType.Imap);

            try
            {
                await service.mailAsync(async (message, index, count) =>
                {
                    await DbValidation(message).ConfigureAwait(false);
                }, number);
            }
            catch (Exception ex)
            {
                Logger($"邮箱:{model.Email}  获取错误:" + ex.Message);
            }
            Logger($"邮箱:{model.Email} 获取完成!");
        }