public static void ReadPop3()
{
using (Pop3Client client = new Pop3Client())
{
if (client.Connected)
{
client.Disconnect();
}
// 连接到服务器,false代表不用ssl
client.Connect("邮件服务器", 110, false);
// 输入邮箱账号和密码
client.Authenticate("账号", "密码");
int messageCount = client.GetMessageCount();
//此处注意,循环遍历邮箱的时候是从1开始的,1代表最早的邮件
for (int i = 1; i <= messageCount; i++)
{
//获取邮件
Message message = client.GetMessage(i);
//获取发件人
string sender = message.Headers.From.DisplayName;
Console.WriteLine("发件人:" + sender);
//获取发件邮箱
string from = message.Headers.From.Address;
Console.WriteLine("发件邮箱:" + from);
//获取收件人
var recive = message.Headers.To;
for (int ace = 0; ace < recive.Count; ace++)
{
RfcMailAddress aaaa = recive[ace];
Console.WriteLine("接收人:" + aaaa.Address);
Console.WriteLine("******************************");
}
Console.WriteLine(@"/");
//获取抄送人
var cc = message.Headers.Cc;
for (int ace = 0; ace < cc.Count; ace++)
{
RfcMailAddress aaaa = cc[ace];
Console.WriteLine("抄送人:" + aaaa.Address);
Console.WriteLine("******************************");
}
//获取主题
string subject = message.Headers.Subject;
Console.WriteLine("主题:" + subject);
//获取发件时间,此处时间为UTC时间,需要手动转换到本地时间
DateTime Datesent = message.Headers.DateSent;
Datesent = Datesent.AddHours(8);
Console.WriteLine("发送日期:" + Datesent);//UTC时区,需要手动转换
//获取接收时间,默认格式类似Fri, 17 Aug 2018 08:07:09 +0800这样,不需要这种格式的必须自己进行转换
string Date = message.Headers.Date;
Console.WriteLine("未格式化日期:" + Date);
CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");
string format = "ddd, d MMM yyyy HH:mm:ss zz00";
DateTime a = DateTime.ParseExact(Date, format, cultureInfo);
Console.WriteLine("接收日期:" + a);
Console.WriteLine("-------------------------------");
//获取邮件内容
MessagePart messagePart = message.MessagePart;
string body = " ";
if (messagePart.IsText)
{
body = messagePart.GetBodyAsText();
}
else if (messagePart.IsMultiPart)
{
MessagePart plainTextPart = message.FindFirstPlainTextVersion();
if (plainTextPart != null)
{
body = plainTextPart.GetBodyAsText();
}
else
{
List<MessagePart> textVersions = message.FindAllTextVersions();
if (textVersions.Count >= 1)
body = textVersions[0].GetBodyAsText();
else
body = "<<OpenPop>> Cannot find a text version body in this message.";
}
Console.WriteLine(body);
Console.WriteLine("===============");
//遍历并获取邮件附件
foreach (MessagePart attachment in message.FindAllAttachments())
{
File.WriteAllBytes(attachment.FileName, attachment.Body);
}
//删除邮件
client.DeleteMessage(messageCount);
// POP3要求您“提交”更改
//通过向服务器发送QUIT命令来完成
client.Dispose();
//也可以通过发送RSET命令重置所有标记的消息。
client.Reset();
}
//关闭连接
client.Disconnect();
}
}
}
番外:如果要把邮件存入数据库的话一定要注意邮件内的特殊字符,比如'号,在存储的时候如果使用手写sql存入的话一定要先把它replace成'',也就是两个单引号,否则会出现无法正常存储的情况