Как отправить Foreach каждый элемент на одно письмо с помощью ASP.NET MVC - PullRequest
0 голосов
/ 30 октября 2019

Я хочу иметь возможность отправить список элементов на один адрес электронной почты. Всякий раз, когда пользователь добавляет элементы в счет-фактуру и нажимает кнопку "Отправить", все элементы должны быть в одном счете-фактуре. Я не понимаю, как мне этого добиться, используя код, который у меня есть в настоящее время. Ниже приведен код, который у меня есть в настоящее время, и я использовал комментарии, чтобы понять код и то, что я пытаюсь достичь: -

public ActionResult SaveOrder(string vat, string grandtotal, string CustId, string emailid, Order[] requesting)
    {
        string result = "Error! Order Is Not Complete!";

        using (mymodel dbb = new mymodel())
        {
            if (vat != null && grandtotal != null)
            {


                var customerId = Guid.NewGuid();
                Ordering ord = new Ordering();
                ord.CustomerId = customerId;
                ord.CustId = CustId;
                ord.EmailId = emailid;
                ord.date_order_placed = DateTime.Now;
                dbb.Orderings.Add(ord);


                if (dbb.SaveChanges() > 0)
                {
                    string order_id = dbb.Orderings.Max(o => o.invoice_number);

                    //the list of items I want to send to the email
                    foreach (var item in requesting)
                    {
                        Invoice_Line_Items in_l_i = new Invoice_Line_Items();

                        in_l_i.invoice_number = order_id;
                        in_l_i.CustId = CustId;
                        in_l_i.department = item.depart;
                        in_l_i.service = item.Service;
                        in_l_i.gender = item.Gender;
                        in_l_i.item = item.Item;
                        in_l_i.quantity = item.Quantity;
                        in_l_i.price = item.price;
                        in_l_i.pick_up_address = item.pick_up_address;
                        in_l_i.pick_up_date = item.pick_up_date;
                        in_l_i.drop_off_address = item.drop_off_address;
                        in_l_i.drop_off_date = item.drop_off_date;
                        in_l_i.pick_up_time = item.pick_up_time;
                        in_l_i.drop_off_time = item.drop_off_time;

                        dbb.Invoice_Line_Items.Add(in_l_i);


                    }

                    invoice_total_slip model = new invoice_total_slip();
                    model.invoice_number = order_id;
                    model.invoice_vat = vat;
                    model.invoice_total = grandtotal;
                    dbb.invoice_total_slip.Add(model);

                    Invoice_Line_Items inn = new Invoice_Line_Items();
                    inn.item = items;

                    if (dbb.SaveChanges() > 0)
                    {
                        //Method to send email 
                        SendVerificationLinkEmail(ord.EmailId, ord.invoice_number, inn.department, inn.service, inn.gender, inn.item, inn.quantity, inn.price, inn.pick_up_address, inn.pick_up_time, inn.pick_up_date, inn.drop_off_address, inn.drop_off_time, inn.drop_off_date);
                        result = "Success! Order Is Complete!";



                    }
                }

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }


            //Code for sending email
           public void SendVerificationLinkEmail(string EmailId, string invoice_number, string depart, string Service, string Gender, string item, string Quantity, string price, string  pick_up_address, string pick_up_time, string pick_up_date, string drop_off_address, string drop_off_time, string drop_off_date)
    {


        var fromEmail = new MailAddress("test@gmail.com", "thokozani");
        var toEmail = new MailAddress(EmailId);
        var fromEmailPassword = "xxxxx"; // Replace with actual password
        string subject = "Your " + invoice_number + " order request has been scheduled ";

        string body = "";

        using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailInvoice.html")))
        {
            body = reader.ReadToEnd();
        }

        //body = body.Replace("{firstname}", firstname);
        //body = body.Replace("{lastname}", lastname);
        body = body.Replace("{emailID}", EmailId);
        body = body.Replace("{pick_up_date}", pick_up_date);
        body = body.Replace("{pick_up_time}", pick_up_time);
        body = body.Replace("{service}", Service);
        body = body.Replace("{invoiceno}", invoice_number);
        body = body.Replace("{Item}", item);
        body = body.Replace("{price}", price);

        body = body.Replace("{pick_up_address}", pick_up_address);
        body = body.Replace("{drop_off_address}", drop_off_address);

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
        };

        using (var message = new MailMessage(fromEmail, toEmail)
        {
            Subject = subject,
            Body = body,
            IsBodyHtml = true
        })
            smtp.Send(message);
    }

1 Ответ

0 голосов
/ 30 октября 2019

не сильно отличается от того, что вы делаете сейчас, вы можете иметь небольшой шаблон для элемента счета, затем циклически перебирать свои элементы и назначать этот шаблон каждому, а затем добавлять его в тело сообщения

string invoiceItemTemplate = "";
StringBuilder invoiceItems = new StringBuilder();

using (StreamReader reader = new StreamReader(Server.MapPath("~/ItemInvoice.html")))
{
   invoiceItemTemplate = reader.ReadToEnd();
}

foreach(var item in items)
{
   var tempInvTemplate = invoiceItemTemplate;
   tempInvTemplate.Replace("{price}", item.Price);
   tempInvTemplate.Replace("{name}", item.Name);

   invoiceItems.Append(tempInvTemplate);
}

body.Replace("{invoiceItems}", invoiceItems.ToString());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...