Exemplo n.º 1
0
        public async Task <bool> SendOrderEmail(string subject, Order order, string email)
        {
            var client     = new SendGridClient(Options.SendGridKey);
            var orderEmail = new OrderEmail
            {
                Order = order
            };
            var content = orderEmail.GetContent();
            var items   = orderEmail.GetItems();

            content = content
                      .Replace("{row}", items)
                      .Replace("{title}", subject)
                      .Replace("{total}", order.PostCouponTotal.ToString("N1"))
                      .Replace("{address}", order.Address)
                      .Replace("{username}", order.User.UserName)
                      .Replace("{orderId}", order.Id.ToString())
                      .Replace("{date}", order.DateCreated.ToLongDateString());
            var msg = new SendGridMessage
            {
                From    = new EmailAddress(Consts.Email.Address, Consts.Email.Sender),
                Subject = subject,
//                TemplateId = "39dfd02b-b1dc-4f26-b032-878c5e4d3b77"
                HtmlContent = content
            };

//            var content = new OrderEmail {Order = order}.GetContent();
//            var p = new Personalization
//            {
//                Substitutions = new Dictionary<string, string>()
//            };
            msg.AddTo(new EmailAddress(email));

            msg.TrackingSettings = new TrackingSettings
            {
                ClickTracking = new ClickTracking {
                    Enable = false
                }
            };

            var response = await client.SendEmailAsync(msg);

            var statusCode = (int)response.StatusCode;

            return(statusCode >= 200 && statusCode < 300);
        }
Exemplo n.º 2
0
        public Result <Order> PostFromTemporary([FromBody] OrderEmail value)
        {
            //TODO: Sprawdź Order przed CreateTemporaryUser
            var U = _userService.CreateTemporaryUser(value.email); //tutaj też wysyłamy emaila
            var R = new Result <Order>();

            if (U.status)
            {
                value.order.UserId            = U.value.UserId;
                value.order.CreateOrderUserId = U.value.UserId;
                R = _orderService.Add(value.order);
                if (R.status)
                {//przesyłamy informacje o temporary userze spowrotem
                    R.value.User = U.value;
                }
                return(R);
            }
            R.status = false;
            R.info   = U.info;
            return(R);
        }
Exemplo n.º 3
0
        private OrderEmail CreateDocumentEmail(string clientName, string organizationName, OrderDocument document)
        {
            if (document.Type == OrderDocumentType.Bill)
            {
                var billDocument     = document as BillDocument;
                var wasHideSignature = billDocument.HideSignature;
                billDocument.HideSignature = false;
                ReportInfo ri = billDocument.GetReportInfo();
                billDocument.HideSignature = wasHideSignature;

                EmailTemplate template = billDocument.GetEmailTemplate();
                OrderEmail    email    = new OrderEmail();
                email.Title    = string.Format("{0} {1}", template.Title, billDocument.Title);
                email.Text     = template.Text;
                email.HtmlText = template.TextHtml;
                foreach (var item in template.Attachments)
                {
                    email.AddInlinedAttachment(item.Key, item.Value.MIMEType, item.Value.FileName, item.Value.Base64Content);
                }

                email.Recipient         = new EmailContact(clientName, yvalidatedentryEmail.Text);
                email.Sender            = new EmailContact(organizationName, ParametersProvider.Instance.GetParameterValue("email_for_email_delivery"));
                email.Order             = document.Order.Id;
                email.OrderDocumentType = document.Type;
                using (MemoryStream stream = ReportExporter.ExportToMemoryStream(ri.GetReportUri(), ri.GetParametersString(), ri.ConnectionString, OutputPresentationType.PDF, true)) {
                    string billDate = billDocument.DocumentDate.HasValue ? "_" + billDocument.DocumentDate.Value.ToString("ddMMyyyy") : "";
                    email.AddAttachment($"Bill_{billDocument.Order.Id}{billDate}.pdf", stream);
                }
                return(email);
            }
            else
            {
                //для других документов не реализована отправка почты
                return(null);
            }
        }
 // POST: api/SendOrder
 public string Post(OrderEmail email)
 {
     return(OrderEmailHelper.sendOrder(email) == true ? "success" : "fail");
 }
Exemplo n.º 5
0
        private void SendDocument()
        {
            var client = document.Order.Client;
            var rdlDoc = (document as IPrintableRDLDocument);

            if (rdlDoc == null)
            {
                MessageDialogHelper.RunErrorDialog("Невозможно распечатать данный тип документа");
                return;
            }

            if (document.Order.Id == 0)
            {
                if (!MessageDialogHelper.RunQuestionDialog("Для отправки необходимо сохранить заказ, сохранить сейчас?"))
                {
                    return;
                }
                if (!(MyOrmDialog as OrderDlg).Save())
                {
                    return;
                }
            }

            if (client == null)
            {
                MessageDialogHelper.RunErrorDialog("Должен быть выбран клиент в заказе");
                return;
            }

            if (!ParametersProvider.Instance.ContainsParameter("email_for_email_delivery"))
            {
                MessageDialogHelper.RunErrorDialog("В параметрах базы не определена почта для рассылки");
                return;
            }

            if (string.IsNullOrWhiteSpace(yvalidatedentryEmail.Text))
            {
                MessageDialogHelper.RunErrorDialog("Необходимо ввести адрес электронной почты");
                return;
            }

            OrderEmail email = CreateDocumentEmail("", "vodovoz-spb.ru", document);

            if (email == null)
            {
                MessageDialogHelper.RunErrorDialog("Для данного типа документа не реализовано формирование письма");
                return;
            }

            using (var uow = UnitOfWorkFactory.CreateWithoutRoot()) {
                var employee = EmployeeRepository.GetEmployeeForCurrentUser(uow);
                email.AuthorId      = employee != null ? employee.Id : 0;
                email.ManualSending = true;
            }

            IEmailService service = EmailServiceSetting.GetEmailService();

            if (service == null)
            {
                return;
            }
            var result = service.SendOrderEmail(email);

            //Если произошла ошибка и письмо не отправлено
            string resultMessage = "";

            if (!result.Item1)
            {
                resultMessage = "Письмо не было отправлено! Причина:\n";
            }
            MessageDialogHelper.RunInfoDialog(resultMessage + result.Item2);

            UpdateEmails();
        }
Exemplo n.º 6
0
        public void ResendEmailWithErrorSendingStatus(DateTime date)
        {
            IEmailService service = EmailServiceSetting.GetEmailService();

            if (service == null)
            {
                return;
            }

            IList <StoredEmail> errorSendedEmails;

            using (var uowLocal = UnitOfWorkFactory.CreateWithoutRoot()) {
                StoredEmail unsendedEmailAlias        = null;
                StoredEmail alreadyResendedEmailAlias = null;

                var dateCriterion = Projections.SqlFunction(
                    new SQLFunctionTemplate(
                        NHibernateUtil.Date,
                        "Date(?1)"
                        ),
                    NHibernateUtil.Date,
                    Projections.Property <StoredEmail>(x => x.SendDate)
                    );
                ICriterion dateResctict   = Restrictions.Eq(dateCriterion, date.Date);
                ICriterion dateResctictGe = Restrictions.Ge(dateCriterion, date.Date);

                var resendedQuery = QueryOver.Of <StoredEmail>()
                                    .Where(Restrictions.EqProperty(Projections.Property <StoredEmail>(x => x.Order.Id), Projections.Property(() => unsendedEmailAlias.Order.Id)))
                                    .Where(x => x.State != StoredEmailStates.SendingError)
                                    .Where(dateResctictGe)
                                    .Select(Projections.Count(Projections.Id()));

                errorSendedEmails = uowLocal.Session.QueryOver <StoredEmail>(() => unsendedEmailAlias)
                                    .Where(x => x.State == StoredEmailStates.SendingError)
                                    .Where(dateResctict)
                                    .WithSubquery.WhereValue(0).Eq(resendedQuery)
                                    .List();

                foreach (var sendedEmail in errorSendedEmails)
                {
                    var billDocument = sendedEmail.Order.OrderDocuments.FirstOrDefault(y => y.Type == OrderDocumentType.Bill) as BillDocument;
                    if (billDocument == null)
                    {
                        continue;
                    }

                    billDocument.HideSignature = false;
                    ReportInfo ri = billDocument.GetReportInfo();

                    var        billTemplate = billDocument.GetEmailTemplate();
                    OrderEmail email        = new OrderEmail {
                        Title             = string.Format("{0} {1}", billTemplate.Title, billDocument.Title),
                        Text              = billTemplate.Text,
                        HtmlText          = billTemplate.TextHtml,
                        Recipient         = new EmailContact("", sendedEmail.RecipientAddress),
                        Sender            = new EmailContact("vodovoz-spb.ru", ParametersProvider.Instance.GetParameterValue("email_for_email_delivery")),
                        Order             = billDocument.Order.Id,
                        OrderDocumentType = OrderDocumentType.Bill
                    };
                    foreach (var item in billTemplate.Attachments)
                    {
                        email.AddInlinedAttachment(item.Key, item.Value.MIMEType, item.Value.FileName, item.Value.Base64Content);
                    }
                    using (MemoryStream stream = ReportExporter.ExportToMemoryStream(ri.GetReportUri(), ri.GetParametersString(), ri.ConnectionString, OutputPresentationType.PDF, true)) {
                        string billDate = billDocument.DocumentDate.HasValue ? "_" + billDocument.DocumentDate.Value.ToString("ddMMyyyy") : "";
                        email.AddAttachment($"Bill_{billDocument.Order.Id}{billDate}.pdf", stream);
                    }
                    email.AuthorId      = sendedEmail.Author.Id;
                    email.ManualSending = sendedEmail.ManualSending ?? false;

                    service.SendOrderEmail(email);
                }
            }
        }