将模板添加到电子邮件Body

时间:2018-03-08 05:46:06

标签: c# asp.net-mvc

我有这样的电子邮件服务:

if (self.appId != nil && self.apiKEY != nil && self.Indices != nil) {
        InstantSearch.shared.configure(appID: "\(self.appId!)", apiKey: "\(self.apiKEY!)", index: "\(self.Indices!)en_products")
        InstantSearch.shared.params.attributesToRetrieve = ["*"]
        InstantSearch.shared.registerAllWidgets(in: self.view)
        if receivedText != nil {
            print(String(describing: receivedText!))
            InstantSearch.shared.searchBar(searchBar, textDidChange: receivedText!)
            InstantSearch.shared.params.attributesToRetrieve = ["*"]
            InstantSearch.shared.registerAllWidgets(in: self.view)
        }else {
            let query = Query()
            query.facets = facetsArray
            print(categoriesArray)
            query.facetFilters = categoriesArray
            query.hitsPerPage = 100
            InstantSearch.shared.searcher.index.search(query, requestOptions: nil, completionHandler: { (data, error) in
                self.lastResults = SearchHits(fromDictionary: data!)
                print(data)
                self.listCollectionView.reloadHits()
            })
        }
        hitsCollectionViews = [self.listCollectionView]
        ActivityIndicator.stopAnimating()
    }
open override func collectionView(_ collectionView: UICollectionView,
                                  cellForItemAt indexPath: IndexPath,
                                  containing hit: [String : Any]) -> UICollectionViewCell {
    //        print(hit)
    let cell: listItemCollectionViewCell
    cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hitCell", for: indexPath) as! listItemCollectionViewCell
    cell.listItemLabel.text = hit["name"] as? String
    cell.listItemPrice.text = hit["price"] as? String
    if let strImage = hit["image_url"] as? String {
        let baseUrl = "http:\(strImage)"
        cell.listItemImg.contentMode = .scaleAspectFit
        cell.listItemImg.kf.indicatorType = .activity
        if URL(string: baseUrl) != nil {
            let resource = ImageResource(downloadURL: URL(string: baseUrl)!, cacheKey: baseUrl)
            cell.listItemImg.kf.setImage(with: resource, placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
        }
        else{
            cell.listItemImg.image = #imageLiteral(resourceName: "placeholder")
        }
    }
    cell.wishListButton.addTarget(self, action: #selector(saleTappedButton(sender:)), for: .touchUpInside)
    cell.listItemStarRating.starBorderColor = UIColor.lightGray
    cell.listItemStarRating.starBorderWidth = 0.5
    return cell
}

然后我执行它进入另一个方法:

DECLARE @i int = 0

WHILE @i < 15
BEGIN
    SET @i = @i + 1
  Select @i 
END

我有模板电子邮件模板,其中的项目为:

public async Task Execute(string email, string subject, string message)
{
    try
    {
        string toEmail = string.IsNullOrEmpty(email)
                         ? _emailSettings.ToEmail
                         : email;
        MailMessage mail = new MailMessage()
        {
            From = new MailAddress(_emailSettings.UsernameEmail, "")
        };
        mail.To.Add(new MailAddress(toEmail));
        mail.CC.Add(new MailAddress(_emailSettings.CcEmail));

        mail.Subject = "Management System - " + subject;
        mail.Body = message;
        mail.IsBodyHtml = true;
        mail.Priority = MailPriority.High;

        using (SmtpClient smtp = new SmtpClient(_emailSettings.PrimaryDomain, _emailSettings.PrimaryPort))
        {
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(_emailSettings.UsernameEmail, _emailSettings.UsernamePassword);
            smtp.EnableSsl = true;
            await smtp.SendMailAsync(mail);
        }
    }
    catch (Exception ex)
    {
        //do something here
    }
}

如何在正文中调用模板并将{{url}}替换为我服务中的某些变量?因此,public Task SendAsync(string email, string subject, string message) { Execute(email, subject, message).Wait(); return Task.FromResult(0); } 更改为<a href="{{url}}" target="_blank" </a>

1 个答案:

答案 0 :(得分:1)

我通常会使用{0}{1}{2}等占位符来保存模板,因为它们直接适合string.Format。因此,在创建电子邮件时,我使用:

而不是编写mail.Body = message
mail.Body = string.Format(template, placeholder1, placeholder2);

我的模板如下:

Hello {0},

... Please <a href="{1}">click here to do XYZ</a>...

现在这个方法有一个缺点,就是你必须记录模板中的{0}对应placeholder1等。

或者,您可以使用稍微详细的占位符,例如{FirstName}{LastName},然后使用template.Replace("{FirstName}", user.FirstName).Replace("{LastName}", user.LastName)在电子邮件正文中替换它们。