LumiSoft收取邮件(含邮件附件)
2015-06-10 13:24 狼人:-) 阅读(611) 评论(1) 编辑 收藏 举报在.NET当中利用C#发送电子邮件很简单,微软也提供了默认的实现,但是收取电子邮件的操作却并没有提供解决方案。好在有一些第三方的解决方案可供选择,来简化程序员日常项目中的开发工作。
这里我选用LumiSoft,下载地址为http://www.lumisoft.ee/lswww/download/downloads/。当你打开链接,会发现里面有很多项目,为了实现收取邮件的功能,我们可以选择Examples里面的pop3_client_app.zip文件。我们解压缩,利用VS打开这个项目运行即可。这是官方提供的一个现成的示例,能够收取邮件并显示。
我们打开这个项目bin目录下的LumiSoft.Net.dll文件,这就是封装好的一个核心dll。我们可以利用.NET Reflector工具查看这个dll里面的类、方法等。
基本上有了官方源代码例子以及Reflector工具,我们就可以利用它进行编程实现了。使用方式很简单,只要在项目中引用LumiSoft.Net.dll这一个文件即可。下面我就直接贴出一段完整的控制台项目代码,实现的是收取邮件(显示)并下载邮件的附件(支持多个附件)到指定目录下的功能。没有漂亮的界面,留给读者自行完善吧。
namespace MailHelper { class Program { static void Main(string[] args) { using (POP3_Client pop3 = new POP3_Client()) { pop3.Connect("pop.qq.com", 995, true); pop3.Login("id", "password");//两个参数,前者为Email的账号,后者为Email的密码 POP3_ClientMessageCollection messages = pop3.Messages; Console.WriteLine("共{0}封邮件", messages.Count); for (int i = 0; i < messages.Count; i++) { POP3_ClientMessage message = messages[i];//转化为POP3 Console.WriteLine("\r\n正在检查第{0}封邮件...", i + 1); if (message != null) { byte[] messageBytes = message.MessageToByte(); Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes); string sender = mime_message.From == null ? "sender is null" : mime_message.From[0].DisplayName; string senderAddress = mime_message.From == null ? "senderAddress is null" : mime_message.From[0].Address; string subject = mime_message.Subject ?? "subject is null"; string recDate = mime_message.Date == DateTime.MinValue ? "date not specified" : mime_message.Date.ToString(); string content = mime_message.BodyText ?? "content is null"; Console.WriteLine("邮件地址为{0}的{1},于{2}发送了主题为{3}的邮件", senderAddress, sender, recDate, subject); Console.WriteLine("内容为{0}", content); MIME_Entity[] attachments = mime_message.GetAttachments(true, true); foreach (MIME_Entity entity in attachments) { if (entity.ContentDisposition != null) { string fileName = entity.ContentDisposition.Param_FileName; if (!string.IsNullOrEmpty(fileName)) { DirectoryInfo dir = new DirectoryInfo(@"D:\email\"); if (!dir.Exists) dir.Create(); string path = Path.Combine(dir.FullName, fileName); MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body; Stream decodedDataStream = byteObj.GetDataStream(); using (FileStream fs = new FileStream(path, FileMode.Create)) { LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000); } Console.WriteLine("{0}已经被下载。", fileName); } } } } } } } } }
效果图:
声明:此博有部分内容为转载,版权归原作者所有~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南