在MVC中发送电子邮件

时间:2014-02-10 11:02:26

标签: c# asp.net-mvc http email nopcommerce

我有一个方法可以从数据库中返回我想要发送到某个电子邮件地址的产品列表。我想发送的方法返回一个项目列表。有一个ContactUs公式可以发送消息,但是从客户到我正考虑用作基础的店主。但是,我想要作为电子邮件发送的数据只能在没有发件人的情况下发送到商店所有者的电子邮件地址。

我想发送从此方法返回的产品列表:

public IList<BestsellersReportLine> DailyBestsellersReport()
{
    OrderStatus os; 
    PaymentStatus? ps = null; 
    ShippingStatus ss;
    int billingCountryId = 0;
    int recordsToReturn = 999; 
    int orderBy = 1;
    int groupBy = 1;

    int? paymentStatusId = null;
    if (ps.HasValue)
        paymentStatusId = (int)ps.Value;

    // Specifies the time range for sold products/day
    var range = new
    {
        startTimeUtc = DateTime.Today.AddDays(-1),
                     endTimeUtc = DateTime.Today.AddSeconds(-1),
                     CreatedOnUtc = DateTime.Today.AddDays(-1),
    };

    var query1 = from opv in _opvRepository.Table
        join o in _orderRepository.Table on opv.OrderId equals o.Id
        join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
        join p in _productRepository.Table on pv.ProductId equals p.Id
        where (o.CreatedOnUtc >= range.startTimeUtc && o.CreatedOnUtc <= range.endTimeUtc) &&
        (!paymentStatusId.HasValue || paymentStatusId == o.PaymentStatusId)
        select opv;

    var query2 = groupBy == 1 ?
        //group by product variants
        from opv in query1
        group opv by opv.ProductVariantId into g
        select new
        {
            EntityId = g.Key,
                     TotalAmount = g.Sum(x => x.PriceExclTax),
                     TotalQuantity = g.Sum(x => x.Quantity),
        }
    :
        //group by products
        from opv in query1
        group opv by opv.ProductVariant.ProductId into g
        select new
        {
            EntityId = g.Key,
                     TotalAmount = g.Sum(x => x.PriceExclTax),
                     TotalQuantity = g.Sum(x => x.Quantity),
        }
    ;

    switch (orderBy)
    {
        case 1:
            {
                query2 = query2.OrderByDescending(x => x.TotalQuantity);
            }
            break;
        case 2:
            {
                query2 = query2.OrderByDescending(x => x.TotalAmount);
            }
            break;
        default:
            throw new ArgumentException("Wrong orderBy parameter", "orderBy");
    }

    if (recordsToReturn != 0 && recordsToReturn != int.MaxValue)
        query2 = query2.Take(recordsToReturn);

    var result = query2.ToList().Select(x =>
            {
            var reportLine = new BestsellersReportLine()
            {
            EntityId = x.EntityId,
            TotalAmount = x.TotalAmount,
            TotalQuantity = x.TotalQuantity
            };
            return reportLine;


            }).ToList();

    //return result;
    return result.OrderBy(opv => opv.TotalQuantity).ToList();
}

作为此方法的电子邮件:

[HttpPost, ActionName("ContactUs")]
[CaptchaValidator]
public ActionResult ContactUsSend(ContactUsModel model, bool captchaValid)
{
    //validate CAPTCHA
    if (_captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage && !captchaValid)
    {
        ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha"));
    }

    if (ModelState.IsValid)
    {
        string email = model.Email.Trim();
        string fullName = model.FullName;
        string subject = string.Format(_localizationService.GetResource("ContactUs.EmailSubject"), _storeInformationSettings.StoreName);

        var emailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
        if (emailAccount == null)
            emailAccount = _emailAccountService.GetAllEmailAccounts().FirstOrDefault();

        string from = null;
        string fromName = null;
        string body = Core.Html.HtmlHelper.FormatText(model.Enquiry, false, true, false, false, false, false);
        //required for some SMTP servers
        if (_commonSettings.UseSystemEmailForContactUsForm)
        {
            from = emailAccount.Email;
            fromName = emailAccount.DisplayName;
            body = string.Format("<strong>From</strong>: {0} - {1}<br /><br />{2}",
                    Server.HtmlEncode(fullName),
                    Server.HtmlEncode(email), body);
        }
        else
        {
            from = email;
            fromName = fullName;
        }
        _queuedEmailService.InsertQueuedEmail(new QueuedEmail()
        {
            From = from,
            FromName = fromName,
            To = emailAccount.Email,
            ToName = emailAccount.DisplayName,
            Priority = 5,
            Subject = subject,
            Body = body,
            CreatedOnUtc = DateTime.UtcNow,
            EmailAccountId = emailAccount.Id
        });

        model.SuccessfullySent = true;
        model.Result = _localizationService.GetResource("ContactUs.YourEnquiryHasBeenSent");

        //activity log
        _customerActivityService.InsertActivity("PublicStore.ContactUs", _localizationService.GetResource("ActivityLog.PublicStore.ContactUs"));

        return View(model);
    }

    model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage;
    return View(model);
}

注意:ContactUs -method是NopCommerce中的默认方法,我尝试改变一些东西,但我没有得到任何东西。我只需要通过“DailyBestsellersReport方法”将从数据库中检索到的产品列表发送到商店所有者的电子邮件地址。

在简单的理论中,我想做这样的事情:

[HttpPost, ActionName("Bestsellers")]
[CaptchaValidator]
public ActionResult SendBestSellersList(BestSellersReportLine model)
{
    DailyBestsellersReport();
}

1 个答案:

答案 0 :(得分:3)

虽然这不是一个直接的答案,如果您正在寻找一个简单的可重用选项,我推荐MVC Mailer,它可以作为NuGet包使用: https://www.nuget.org/packages/MvcMailer

还有一个很好的步骤,任何人都可以随时了解 -

https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide

另一个教程:

http://www.hanselman.com/blog/NuGetPackageOfTheWeek2MvcMailerSendsMailsWithASPNETMVCRazorViewsAndScaffolding.aspx