您的位置:首页 > 运维架构

.net利用pop3组件接收邮件(包含附件的下载)

2011-11-03 16:44 543 查看
网上有很多利用pop3,jmail组件来接收邮件和附件的.但代码都是有点晕头,一次运行不成功能.这里我也找了写资料写了一demo,测试过,木有问题.可以直接使用.后续将对已读和未读邮件进行筛选. (打算用vs自带的mail组件或者smtp在写一个demo),望大家互相交流一下.优化一下代码,这个demo只是雏形 .

首先应现在项目中引用LumiSoft.Net.dll 文件

protected void Page_Load(object sender, EventArgs e)

{ List<Mime> dd =GetEmails(); //dd中就可以查找出邮件的内容、主题、发件人等信息。你可以通过调试状态的快速监视查看 foreach (Mime mdd in dd) { //页面输出邮件内容 ShowEmail(mdd); } } //获得邮件列表 public List<Mime> GetEmails() {
//需要首先设置这些信息 string pop3Server = "pop.sina.com.cn"; //邮箱服务器 如:"pop.sina.com.cn";或 "pop.qq.com" 好像sina的比较快 int pop3Port = 110; //端口号码 用"110"好使。最好看一下你的邮箱服务器用的是什么端口号 bool pop3UseSsl = false; string username = ""; //你的邮箱用户名 string password = ""; //你的邮箱密码 List<string> gotEmailIds=new List<string>(); List<Mime> result=new List<Mime>(); using (POP3_Client pop3 = new POP3_Client()) { //与Pop3服务器建立连接 pop3.Connect(pop3Server, pop3Port, pop3UseSsl); //验证身份 pop3.Authenticate(username, password, false); //获取邮件信息列表 POP3_ClientMessageCollection infos = pop3.Messages; foreach (POP3_ClientMessage info in infos) { //每封Email会有一个在Pop3服务器范围内唯一的Id,检查这个Id是否存在就可以知道以前有没有接收过这封邮件 if (gotEmailIds.Contains(info.UID)) continue; //获取这封邮件的内容 byte[] bytes = info.MessageToByte(); //记录这封邮件的Id gotEmailIds.Add(info.UID); //解析从Pop3服务器发送过来的邮件信息 Mime mime = Mime.Parse(bytes); result.Add(mime); } } return result; } // 主要显示邮件内容

public void ShowEmail(Mime m) { //获取附件 foreach (MimeEntity entry in m.Attachments) { string fileName = entry.ContentDisposition_FileName; //获取文件名称 string path = Server.MapPath("~\\Attch\\" + fileName); if (File.Exists(path)) { Random random = new Random(); int newfile = random.Next(1, 100000); path = Server.MapPath("~\\Attch\\" + newfile.ToString()); Directory.CreateDirectory(path); path += "\\" + fileName; } byte[] data = entry.Data; FileStream pFileStream = null; pFileStream = new FileStream(path, FileMode.Create); pFileStream.Write(data, 0, data.Length); pFileStream.Close(); } Response.Write("From:"+m.MainEntity.From.ToAddressListString()); Response.Write("To:"+m.MainEntity.To.ToAddressListString()); Response.Write("Time:"+ m.MainEntity.Date); //发送时间 Response.Write("Subject:"+ m.MainEntity.Subject); //主题 Response.Write("Plain Body:"+ m.BodyText); //内容 Response.Write("Html Body:"+ m.BodyHtml); //HTML格式内容 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: