在控制台应用程序中发送Html Mail

时间:2013-11-27 09:35:48

标签: .net email c#-4.0

我创建了一个控制台应用程序来发送邮件,现在我有html模板 我现在根据用户从数据库获取数据如何在html中绑定这些数据。 我的代码是

    private static void Main(string[] args)
    {
        // Get All User
        var userList = BLLMailAlert.GetAllSubscribedUser();
        // Send UserID as Parameter and Find Tenders For Users
        foreach (var user in userList)
        {
            BLLMailAlert.GetAllTenderForPaidUser(user.UserID);

            // For Each AlertId Find Template Name and EmailId
            foreach (var usr in userList)
            {
                var detail = BLLMailAlert.GetUserAllDetail(usr.AlertID);

                // According to TemplateName FIND Template and Write Tender in that Template
                switch (usr.UserTypeTemplate.TemplateType.TemplateTypeName)
                {
                    case "TemplateForPaidUser.htm":
                    {
                        // Send Template in Mail To Each User
                        var fromEmail = string.Empty;
                        var toEmail = string.Empty;
                        toEmail = usr.Email;
                        fromEmail = Convert.ToString(ConfigurationManager.AppSettings["adminmail"]);
                        const string TemplatePath = "[Path to resource]";
                        var mailContent = new StreamReader(TemplatePath).ReadToEnd();
                        mailContent += detail;
                        BLLMailAlert.SendTenderAlert(fromEmail, toEmail, mailContent);
                    }

                        break;
                }
            }
        }
    }

    //function to send mail
    // I have Class named Mail which i am using to send mail
    public static bool SendTenderAlert(string fromEmail, string toEmail, string mailContent)
    {
        try
        {
            var currentDate = System.DateTime.Now.Date;
            Mail.SendHtmlMail(fromEmail, toEmail, "TenderKhabar | Fresh Tenders Of |" + currentDate, mailContent);
            return true;
        }
        catch
        {
            return false;
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用String.Replace。每个人都这样做。它听起来可能不优雅,但它有很多优点

  1. 您不需要了解文档格式,只需替换字符串
  2. 模板格式可能会更改,但您的代码保持不变。
  3. 在我的公司,我们通常使用大括号Dear <strong>{Customer.Name}</strong>,但它可以是Dear <strong>$(Customer.Name)</strong>,

    在一个案例中,我必须为模板编写代码iffor s,并且我使用了正则表达式和字符串替换。