.NET发送邮件和接收邮件
2013-08-04 18:24
393 查看
lumisoft 类库可以到 http://www.lumisoft.ee/lsWWW/download/downloads/Net下载
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using LumiSoft.Net.Mime; using LumiSoft.Net.POP3.Client; using LumiSoft.Net.MIME; using LumiSoft.Net.SMTP.Client; using System.Data.SqlClient; using Microsoft.Practices.EnterpriseLibrary.Data; using System.IO; using System.Text.RegularExpressions; using System.Text; using System.Xml; using System.Collections.Generic; using System.Diagnostics; /// <summary> /// Summary description for POP3Email /// </summary> /// public class POP3Email { public POP3Email() { // // TODO: Add constructor logic here // } #region 字段属性 private static string from { get; set; } private static string name { get; set; } private static string area { get; set; } private static string position { get; set; } private static string uniqueID { get; set; } #endregion #region 接收邮件方法 public static void ReceiverEmail(string host, int port, bool ssl, string userName, string pass,string email) { POP3_Client client = new POP3_Client(); List<Mime> mime = new List<Mime>(); string rootDirec = ConfigurationManager.AppSettings["EmailSave"]; string userDirec = AppDomain.CurrentDomain.BaseDirectory + "\\"+rootDirec; if (!Directory.Exists(rootDirec)) { Directory.CreateDirectory(rootDirec); } if (Dic_resume_base.Count == 0) { InitialDic(); } if (!identDic.Keys.Contains(email)) //程序第一次执行时执行该操作 { GetEmailIdent(email); } try { //与POP3服务进行连接 client.Connect(host, port, ssl); //身份验证 client.Authenticate(userName, pass, true); POP3_ClientMessageCollection msgCollections = client.Messages; //获取邮箱里面的所有邮件 foreach (POP3_ClientMessage msg in msgCollections) { if (identDic[email].Contains(msg.UID)) //如果集合已经存在改邮件ID标识,那么就继续循环不对该邮件操作。 { continue; } if (InsertIdent(msg.UID, email)) { uniqueID = msg.UID; identDic[email].Add(msg.UID);//记录邮件的ID标识 } byte[] bytes = msg.MessageToByte();//读取邮件里的内容 Mime m = Mime.Parse(bytes);//解析从POP3服务器发送过来的邮件信息 if (!RegValidata(m.MainEntity.Subject))//验证如果不是招聘网投递过来的简历不进行文件保存 { continue; } string attacht = "";//附件名 string content = "";//正文 if (m != null) { string mail_from = ""; string mail_formName = ""; if (m.MainEntity.From != null) { for (int i = 0; i < m.MainEntity.From.Count; i++) { if (i == 0) { mail_from = (m.MainEntity.From).Mailboxes[i].EmailAddress; } else { mail_from = string.Format(",{0}", (m.MainEntity.From).Mailboxes[i].EmailAddress); } mail_formName = (m.MainEntity.From).Mailboxes[0].DisplayName != "" ? (m.MainEntity.From).Mailboxes[0].DisplayName : (m.MainEntity.From).Mailboxes[0].LocalPart; } } string mail_to = ""; string mail_toCollection = ""; if (m.MainEntity.To != null) { mail_toCollection = m.MainEntity.To.ToAddressListString(); for (int i = 0; i < m.MainEntity.To.Mailboxes.Length; i++) { if (i == 0) { mail_to = (m.MainEntity.To).Mailboxes[i].EmailAddress; } else { mail_to += string.Format("{0}", (m.MainEntity.To).Mailboxes[i].EmailAddress); } } } SaveInfo(m.BodyHtml); //为接收邮箱配置个人目录 if (!Directory.Exists(userDirec)) { Directory.CreateDirectory(userDirec); } //把接收的内容存在至文件夹 string userFile = userDirec + "\\" + msg.UID + ".html"; Regex rg_modif_url = new Regex("(\")(.*?\\.jpg)");//正则表达式修改内容的图片路径 using (FileStream fs = File.Open(userFile, FileMode.Create)) { StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); sw.Write(rg_modif_url.Replace(m.BodyHtml, "$1Attachments\\$2")); sw.Flush(); sw.Close(); } } //获取并保存附件 string path = userDirec + "\\" + "Attachments"; foreach (MimeEntity entry in m.Attachments) { string fileName = entry.ContentDisposition_FileName; //获取附件名称 if (!Directory.Exists(path))//不存在文件夹则创建一个新的文件夹 { Directory.CreateDirectory(path); } string filePath = path + "\\" + fileName; if (File.Exists(filePath)) { continue; //Random random = new Random(); //int newfile = random.Next(1, 100000); //filePath = path + "\\" + newfile.ToString() + (m.MainEntity.From).Mailboxes[0].DisplayName + fileName; } byte[] data = entry.Data; FileStream pFileStream = null; pFileStream = new FileStream(filePath, FileMode.Create); pFileStream.Write(data, 0, data.Length); pFileStream.Close(); } } } catch (Exception e) { throw e; } finally { client.Dispose(); } } #endregion //获取所有被设置为接收的邮箱 public static DataTable GetReceivers() { string sql = "SELECT * FROM Email WHERE e_emailStatu=0"; Database db = DatabaseFactory.CreateDatabase(); DataTable dt = db.ExecuteDataSet(CommandType.Text, sql).Tables[0]; return dt; } private static string template { get; set; }//模板 private static bool RegValidata(string sourceText) { string patternZP = @"^((?'from'.*))(?:应聘)(?'pos'.*)-(?'area'.*)-(?'name'.*)$"; string pattern51 = @"(^\((?'from'.*)\)申请贵公司(?'pos'.*)((?'area'.*))-(?'name'.*)$|^((?'from'.*))(?:应聘)(?'pos'.*)-(?'area'.*)-(?'name'.*)$)"; Regex regZP = new Regex(patternZP); Regex reg51 = new Regex(pattern51); bool flag = false; Match match = null; if (reg51.IsMatch(sourceText)) { template = "51job"; flag = true; match = reg51.Match(sourceText); } else if (regZP.IsMatch(sourceText)) { template = "zhaopin"; flag = true; match = regZP.Match(sourceText); } else { flag = false; } if (match != null){ from = match.Groups["from"].Value; name = match.Groups["name"].Value; area = match.Groups["area"].Value; position = match.Groups["pos"].Value; } return flag; } private static Dictionary<string, List<string>> identDic = new Dictionary<string, List<string>>(); private static void GetEmailIdent(string email) { List<string> identList = new List<string>(); Database db = DatabaseFactory.CreateDatabase(); string sql = "SELECT Ident FROM EmailIdent WHERE Email='" + email+"'"; IDataReader reader = db.ExecuteReader(CommandType.Text, sql); while (reader.Read()) { identList.Add(reader["Ident"].ToString()); continue; } identDic.Add(email, identList); } //想数据库插入标识 private static bool InsertIdent(string ident,string email) { string sql = "INSERT EmailIdent(Ident,Email) VALUES ('" + ident + "','"+email+"')"; Database db = DatabaseFactory.CreateDatabase(); return db.ExecuteNonQuery(CommandType.Text, sql)>0; } /// <summary> /// 把简历信息持久化 /// </summary> /// <param name="body">邮件的内容</param> private static List<Dictionary<string, string>> alist = new List<Dictionary<string, string>>(); /// <summary> /// 将简历内容保存至数据库 /// </summary> /// <param name="bodyHtml">简历内容主体</param> /// <returns>是否插入成功!</returns> private static bool SaveInfo(string bodyHtml) { bodyHtml = new Regex("(^\\s*|\\r|\\n|\\t|( ))").Replace(bodyHtml,""); if (template=="51job") { //判断51job是旧版或者新版的简历模板 if (new Regex("\\|[男|女]\\|").IsMatch(bodyHtml)) { template += "02"; } } //获取模板 XmlDocument doc = new XmlDocument(); string webRoot = System.AppDomain.CurrentDomain.BaseDirectory; string path = "Web\\Modules\\Email\\XMLtemplate\\"+template+".xml"; path = Path.Combine(webRoot, path); doc.Load(path); XmlElement element = doc.DocumentElement; string xpath = "a:Value"; XmlNodeList nodeList = element.GetElementsByTagName(xpath); Dictionary<string, string> regDic = new Dictionary<string, string>();//保存正则表达式的集合 foreach (XmlNode pNode in nodeList) { string key = ""; string value = ""; foreach (XmlNode childNode in pNode.ChildNodes) { if(childNode.LocalName != "AlgExp" && childNode.LocalName != "AttName"){ continue; } if (childNode.LocalName == "AlgExp") { value = childNode.InnerText.Trim(); continue; } if (childNode.LocalName == "AttName") { key = childNode.InnerText.Trim(); continue; } continue; } regDic.Add(key, value); continue; } Dictionary<string, string> dic_result_base = new Dictionary<string, string>(); foreach (string key in regDic.Keys) { if (Dic_resume_base.ContainsKey(key))//基础数据集合跟正则表达式集合对应键值是否相等 { Regex reg = new Regex(regDic[key]); Match match = reg.Match(bodyHtml); string value = match.Groups["attname"].Value==""?"未填写":match.Groups["attname"].Value; dic_result_base.Add(Dic_resume_base[key], value); continue; } } //获取工作经验信息部分代码 doc = new XmlDocument(); path = "Web\\Modules\\Email\\XMLtemplate\\DataField.xml"; doc.Load(Path.Combine(webRoot, path)); element = doc.DocumentElement; xpath = "//regExp/reg"; nodeList = element.SelectNodes(xpath); string temp = bodyHtml; MatchCollection mColle = null; foreach (XmlNode node in nodeList) { Regex rg = new Regex(node.InnerText.Trim(), RegexOptions.Multiline | RegexOptions.IgnoreCase); if (node.Attributes["type"].Value == "replace") { temp = rg.Replace(temp, node.Attributes["rValue"].Value); } else { if (node.Attributes["isEnd"].Value == "yes") { mColle = rg.Matches(temp); } else { temp = rg.Match(temp).Groups["attname"].Value; } } continue; } List<List<string>> list_work = new List<List<string>>(); Regex reg_date = new Regex("\\d+/\\d+--\\d+/\\d+[:|:]"); string tempStr = ""; if (mColle != null && mColle.Count > 0) { List<string> list_info = new List<string>(); for (int i = 0; i < mColle.Count; i++) { if (reg_date.IsMatch(mColle[i].Groups["attname"].Value) && list_info.Count !=0) { if (list_info.Count == 4) { list_work.Add(list_info); } else { list_info.RemoveRange(4, list_info.Count-4); list_info[list_info.Count - 1] = list_info[list_info.Count - 1] + tempStr; list_work.Add(list_info); tempStr = ""; } i--; list_info = new List<string>(); } else { list_info.Add(mColle[i].Groups["attname"].Value); } if (list_info.Count > 4) { tempStr += "\n" + mColle[i].Groups["attname"].Value; } if (i == mColle.Count-1) { if (list_info.Count == 4) { list_work.Add(list_info); } else { list_info.RemoveRange(4, list_info.Count - 4); list_info[list_info.Count - 1] = list_info[list_info.Count - 1] + tempStr; list_work.Add(list_info); tempStr = ""; } } } } //构造SQL语句把数据保存 StringBuilder sb = new StringBuilder(); string bb4b sql_base = @"INSERT INTO Resume_baseInfo ([name],sex,birthdate,nativePlace,address,diploma,specialized,stature,marriage,jobObjective,workYear,[from],area,emailAddress,uniqueID,position,telphone,school,workExperience,projectExperience) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}');"; sql_base = string.Format(sql_base, name, dic_result_base["sex"], dic_result_base["birthdate"], dic_result_base["nativePlace"], dic_result_base["address"], dic_result_base["diploma"], dic_result_base["specialized"], dic_result_base["stature"], dic_result_base["marriage"], dic_result_base["jobObjective"], dic_result_base["workYear"], from, area, dic_result_base["emailAddress"], uniqueID, position, dic_result_base["telphone"], dic_result_base["school"], FormatString(dic_result_base["workExperience"]), FormatString(dic_result_base["projectExperience"])); sb.Append(sql_base); string sql_workExp = @"INSERT INTO resume_workExperience(uniqueID,dateAndPlace,trade,department,duty)VALUES('{0}','{1}','{2}','{3}','{4}');"; for (int i = 0; i < list_work.Count; i++) { for (int j = 0; j < list_work[i].Count; j++) { string dateAndPlace = list_work[i][j]; string trade = list_work[i][++j]; string department = list_work[i][++j]; string duty = list_work[i][++j].Replace("'","''"); string tempSql = string.Format(sql_workExp, uniqueID, dateAndPlace, trade, department, duty); sb.Append(tempSql); } } Database db = DatabaseFactory.CreateDatabase(); return db.ExecuteNonQuery(CommandType.Text, sb.ToString()) > 0; } private static string FormatString(string str) { Regex reg = new Regex("(<.*?>)"); str = reg.Replace(str, ""); reg = new Regex("'"); str = reg.Replace(str, "‘"); reg = new Regex("\""); str = reg.Replace(str, "“"); return str; } private static Dictionary<string, string> Dic_resume_base = new Dictionary<string, string>(); /// <summary> /// 初始化字典数据保持数据库跟简历信息一一对应 /// </summary> private static void InitialDic() { XmlDocument doc = new XmlDocument(); string webRoot = System.AppDomain.CurrentDomain.BaseDirectory; string path = "Web\\Modules\\Email\\XMLtemplate\\DataField.xml"; path = Path.Combine(webRoot, path); doc.Load(path); XmlElement elem = doc.DocumentElement; string xpath = "//baseinfo/field"; XmlNodeList nodeList = elem.SelectNodes(xpath); foreach (XmlNode node in nodeList) { Dic_resume_base.Add(node.Attributes["key"].Value, node.Attributes["value"].Value); continue; } } #region 发送邮件方法 public static void SendEmail(string host,int port,bool ssl,string username,string pass,string from,string[] tos,string subject,string content) { SendEmail(host,port,ssl,username,pass,from,tos,subject,content,null); } /// <summary> /// 邮件的发送方法 /// </summary> /// <param name="host"></param> /// <param name="port">端口</param> /// <param name="ssl">SSL验证</param> /// <param name="username">邮箱登录名</param> /// <param name="pass">邮箱登录密码</param> /// <param name="from">发送邮箱的地址</param> /// <param name="tos">接收邮箱的地址集合,支持群发单发</param> /// <param name="subject">邮件的标题</param> /// <param name="content">邮件的内容</param> /// <param name="attchs">附件、支持多附件发送</param> public static void SendEmail(string host, int port, bool ssl, string username, string pass, string from, string[] tos, string subject,string content, Dictionary<string, Stream> attchs) { foreach (string to in tos) { using (SMTP_Client smtp = new SMTP_Client()) { smtp.Connect(host, port, ssl); smtp.Authenticate(username, pass); smtp.MailFrom(from, -1); smtp.RcptTo(to); MemoryStream stream = CreateMessage(from,to, subject, content, attchs); smtp.SendMessage(stream); } } } private static MemoryStream CreateMessage(string from,string to,string subject,string content,Dictionary<string,Stream> attchs) { Mime mime = new Mime(); MimeEntity mailEntity = mime.MainEntity; mailEntity.From = new AddressList(); mailEntity.From.Add(new MailboxAddress(from)); mailEntity.To = new AddressList(); mailEntity.To.Add(new MailboxAddress(to)); mailEntity.ContentType = MediaType_enum.Multipart_mixed; mailEntity.Subject = subject; MimeEntity textEntity = new MimeEntity(); textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.Base64; textEntity.ContentType = MediaType_enum.Text_html; textEntity.DataText = content; mailEntity.ChildEntities.Add(textEntity); if (attchs != null && attchs.Count != 0) { foreach (string key in attchs.Keys) { MimeEntity attchEntity = new MimeEntity(); string postfix = key.Substring(key.LastIndexOf('.') + 1); //判断文件后缀名适合使用那中格式发送 switch (postfix.ToLower()) { case "jpg": case "jpeg": attchEntity.ContentType = MediaType_enum.Image_jpeg; break; case "gif": attchEntity.ContentType = MediaType_enum.Image_gif; break; case "xml": attchEntity.ContentType = MediaType_enum.Text_xml; break; case "html": attchEntity.ContentType = MediaType_enum.Text_html; break; case "txt": attchEntity.ContentType = MediaType_enum.Text; break; default: attchEntity.ContentType = MediaType_enum.Application_octet_stream; break; } attchEntity.ContentDisposition = ContentDisposition_enum.Attachment; attchEntity.ContentTransferEncoding = ContentTransferEncoding_enum.Base64; attchEntity.ContentDisposition_FileName = key; attchEntity.DataFromStream(attchs[key]); mailEntity.ChildEntities.Add(attchEntity); continue; } } MemoryStream ms = new MemoryStream(); mime.ToStream(ms); ms.Position = 0; return ms; } #endregion }
相关文章推荐
- asp.net 2.0发送和接收邮件总结
- asp.net利用Jmail发送邮件和接收全部代码
- ASP.NET中常用功能代码总结(7)——利用Jmail发送和接收邮件
- asp.net 2.0发送和接收邮件总结
- ASP.NET中常用功能代码总结(7)——利用Jmail发送和接收邮件
- Asp.Net Forums之邮件发送
- windows下使用perl Net:SMTP_auth发送邮件
- ASP.NET Core发送邮件的方法
- 用Javamail写的邮件接收程序和发送程序
- asp.net发送邮件实现方法
- vs.net发送邮件(2.0)
- 怎么样使用JavaMail发送和接收邮件
- ASP.Net环境下使用Jmail组件发送邮件
- System.Net.Mail 邮件发送示例
- System.Net.Mail 发送邮件(带附件)
- asp.net发送邮件示例
- c#发送邮件之System.Net.Mail方法
- asp.net发送邮件
- 使用jMail组件发送邮件(.NET)
- ASP.NET C# 邮件发送全解