using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Xml;
namespace EmailTemplte.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Test()
{
//Sendemail();
//var tpls = CreateEmailTemplate();
//foreach (var tpl in tpls)
//{
// CreateSendEmail(tpl.Subject, tpl.Body, "", tpl.To, tpl.Cc, tpl.Bcc, tpl.ReplyTo, tpl.Priority);
//}
return View();
}
public static List<EmailTemplate> CreateEmailTemplate()
{
List<EmailTemplate> ets = new List<EmailTemplate>();
// 根据类型确认模板
var infos = ConfirmTemplate();
if (infos != null)
{
foreach (var item in infos)
{
ets.Add(new EmailTemplate(item));
}
return ets;
}
else
{
return null;
}
}
public static string CreateSendEmail(string subject, string body, string from, List<string> to, List<string> cc = null, List<string> bcc = null, List<string> replyTo = null, MailPriority pri = MailPriority.Normal)
{
//if (to == null)
// throw new ArgumentNullException("Email To cannot be null");
//if (cc == null)
// cc = new List<string> { };
//if (bcc == null)
// bcc = new List<string> { };
//if (replyTo == null)
// replyTo = new List<string> { };
try
{
String connString = "Data Source = .; Initial Catalog = EmailTest;User ID = "";Pwd = """;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
String sql = "insert into SendEmailInfo values('" + subject + "','" + body + "','" + "" + "','" + "" + "','" + "" + "','"+""+"','" + "123456" + "')";
SqlCommand cmd = new SqlCommand(sql, conn);
int num = (int)cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
//logger.Error(ex);
return string.Empty;
}
return "";
}
public static List<EmailSendInfo> ConfirmTemplate()
{
List<EmailSendInfo> emails = null;
emails = new List<EmailSendInfo>()
{
new EmailSendInfo()
{
TemplateName = "Approved",
To = new List<string> {""},
Cc= new List<string> {""},
Params = new Dictionary<string,string>
{
{"AssignedGroupEN", "jing"}, // {"AssignedGroupEN", arEmail.cChr_Submitter},
{"AssignedGroupCN", "jing"}, // {"AssignedGroupCN", arEmail.cChr_Submitter},
{"RequestId","123456"},
{"Submitter","jing"}, //{"Submitter",arEmail.cChr_Submitter},
}
}
};
return emails;
}
public class EmailTemplate // abstract
{
private static readonly string BccStr = "";
public static Dictionary<string, string> Templates = new Dictionary<string, string>();
public EmailTemplate(EmailSendInfo info)
{
SimpleTemplateEngine engine = new SimpleTemplateEngine();
engine.ProceedTemplate(GetTemplate(info.TemplateName), info.Params);
Body = engine.ProcessedText.ToString();
Subject = GetTitle(Body);
To = info.ToEmails;
Cc = info.CcEmails;
}
private string GetTemplate(string name)
{
string temp;
if (Templates.TryGetValue(name, out temp)) return temp;
lock (Templates)
{
if (Templates.TryGetValue(name, out temp)) return temp;
temp = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath("~/" + System.IO.Path.Combine("Template", name + ".htm")), Encoding.UTF8);
Templates.Add(name, temp);
return temp;
}
}
private string GetTitle(string template)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(template);
return xml.SelectSingleNode("html/head/title").InnerXml;
}
public virtual string Subject { get; protected set; }
public virtual string Body { get; protected set; }
public List<string> To { get; set; }
public List<string> Cc { get; set; }
// If Bcc is defined in schedule.xml, we sent the mail bcc to the specific person(s)
public virtual List<string> Bcc
{
get
{
if (!string.IsNullOrWhiteSpace(BccStr))
return BccStr.Split(';').ToList();
else
return new List<string>();
}
}
// By default, we set mail reply to as mail to
// in order to prevent no one reply system email by incident
public virtual List<string> ReplyTo { get { return To; } }
public virtual MailPriority Priority { get { return MailPriority.Normal; } }
}
class SimpleTemplateEngine
{
private string template;
private Dictionary<string, string> entities;
public void ProceedTemplate(string template, Dictionary<string, string> entities)
{
if (entities == null || entities.Count == 0)
throw new ArgumentException("entities cannot be null or empty.");
this.template = template;
this.entities = entities;
InitTemplateInternal();
}
private void InitTemplateInternal()
{
string value;
StringBuilder buffer = new StringBuilder(template);
foreach (Match match in Regex.Matches(template, "{[^:}]+}"))
{
if (entities.TryGetValue(match.Value.Trim('{', '}'), out value))
{
buffer.Replace(match.Value, System.Web.HttpUtility.HtmlEncode(value));
}
}
ProcessedText = buffer;
}
public StringBuilder ProcessedText { get; private set; }
}
public class EmailSendInfo
{
public string TemplateName { get; set; }
public Dictionary<string, string> Params { get; set; }
public List<string> To { get; set; }
public List<string> Cc { get; set; }
public List<string> ToEmails { get; set; }
public List<string> CcEmails { get; set; }
public List<string> ToFullNames { get; set; }
public List<string> CcFullNames { get; set; }
}
public void Sendemail()
{
string content = "";
String connString = "Data Source = .; Initial Catalog = EmailTest;User ID = sa;Pwd = sa123";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
String sql = "select body from SendEmailInfo where id=1";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet(); //创建DataSet实例
sda.Fill(ds, "emp"); //把数据填充到临时表里
content = ds.Tables[0].Rows[0][0].ToString();
conn.Close();
using (var smtp = new SmtpClient(""))
{
var mail = new MailMessage();
mail.From = new MailAddress("", "Register");
mail.To.Add("huiminj@wicrenet.com");
mail.Subject = "Register email";
StringBuilder contentBuilder = new StringBuilder();
//contentBuilder.Append("请单击以下链接完成激活(3分钟有效期)</br>");
//contentBuilder.Append("<a href='http://localhost:28559/home/RegisterbyEmai?uid=" + uid + "'>激活账户</a>");
mail.Body = content.ToString();//拼接字符串
mail.SubjectEncoding = Encoding.UTF8;
mail.BodyEncoding = Encoding.UTF8;
mail.IsBodyHtml = true;
//mail.Attachments.Add(new Attachment(@"E:\123.txt"));
smtp.UseDefaultCredentials = false;
//某些SMTP服务器可能不支持SSL,会抛出异常
//smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("", "");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
//emailStatus = "Success";
}
}
}
}