在.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这一个文件即可。下面我就直接贴出一段完整的控制台项目代码,实现的是收取邮件(显示)并下载邮件的附件(支持多个附件)到指定目录下的功能。没有漂亮的界面,留给读者自行完善吧。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
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);
}
}
}
}
}
}
}
}
}
|
效果图:
本文转自 guwei4037 51CTO博客,原文链接:http://blog.51cto.com/csharper/1381344