如何通过正文中的数据库发送带有行的交易电子邮件

时间:2019-01-10 16:07:59

标签: c# asp.net-mvc entity-framework email sendgrid

我正在努力在具有商店功能的网站上发送订单确认-几乎都是定制设计的。我希望在下订单后就发送一封电子邮件,最好是简短地概述/概述所订购的物品。

我已经设法到达订单提交触发电子邮件发送给用户的地步,所以一切都很好。但是,我的问题是如何以某种方式自定义电子邮件正文,使其包含已订购商品的列表?

很高兴从我的控制器中添加代码,尽管我真的不认为这会增加多少价值,因为这更多是一个方法问题,而不是我遇到的问题。

int orderID = order.ID;
var lineItems = DATADB.LineItemList.Where(x => x.OrderNumber == 0 && x.UserID == userID);
lineItems.ForEach(l => l.OrderNumber = orderID);
DATADB.SaveChanges();

// send order confirmation email
var orderConfirmation = DATADB.LineItemList.Where(x => x.OrderNumber == orderID).ToList();
var ordered = string.Join(",", lineItems);
var msg = new SendGridMessage();
msg.From = new System.Net.Mail.MailAddress("orders@freshNclean.ch", "freshNclean");
msg.AddTo(UserManager.FindById(userID).Email);
msg.Subject = "Deine Bestellung bei freshNclean";
msg.Text = "Hi " + UserManager.FindById(userID).FirstName.ToString() + "! Vielen Dank für Deine Bestellung." + ordered;

// SendGrid credentials
var credentials = new NetworkCredential(ConfigurationManager.AppSettings["SGaccount"], ConfigurationManager.AppSettings["SGpassword"]);
var transportWeb = new Web(credentials);
if (transportWeb != null)
{
    transportWeb.DeliverAsync(msg);
}
else
{
    Trace.TraceError("Web Transport konnte nicht generiert werden - die Nachricht wurde nicht versandt.");
    Task.FromResult(0);
}

1 个答案:

答案 0 :(得分:1)

第1步:以对象形式(如果可能的话,以XML格式)获取数据。

步骤2:创建XSLT模板以将该XML格式转换为HTML

参考:Simplest way to transform XML to HTML with XSLT in C#?

public static string TransformXMLToHTML(string inputXml, string xsltString)
{
    XslCompiledTransform transform = new XslCompiledTransform();
    using(XmlReader reader = XmlReader.Create(new StringReader(xsltString))) {
        transform.Load(reader);
    }
    StringWriter results = new StringWriter();
    using(XmlReader reader = XmlReader.Create(new StringReader(inputXml))) {
        transform.Transform(reader, null, results);
    }
    return results.ToString();
}

步骤3:将HTML内容设置为先前方法的输出:

        var apiKey = some-api-key;
        var client = new SendGridClient(apiKey);
        var from = new EmailAddress("test@example.com", "Example User");
        var subject = "Sending with SendGrid is Fun";
        var to = new EmailAddress("test@example.com", "Example User");
        var plainTextContent = "and easy to do anywhere, even with C#";
        var htmlContent = GetHTMLFromXML();
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
        var response = await client.SendEmailAsync(msg);

希望这会有所帮助。