摘要:最近一个项目需要使用到多台服务器的一个备份mail通知后出一个汇总报告再mail给相关技术,所以网上查了多方资料很多都没用,在此将测试OK(QQ邮箱/163网易邮箱)的程式以及说明备份一下......
特别注意4.5的项目必须使用MailKit 2.15.0版本支持
using MailKit;
using MailKit.Net.Imap;
using MailKit.Search;
using MimeKit;
using System;
using System.Linq;
using System.Security.Authentication;
namespace CheckBackupEmail
{
public class ReadMailClass
{
//备注说明连接gmail邮件必须使用SslStream
//POP试试
//string outDirPath= Application.StartupPath; //附件输出路径
/// <summary>
/// ExceptionHandler
/// </summary>
public static ExceptionHandler handler = new ExceptionHandler();
[Obsolete]
public void test()
{
//Connect();
Connection("imap.qq.com",993);
Console.WriteLine("结束运行");
}
[Obsolete]
public void Connection(string serveraddress, int port)
{
//可测试IMAP连接是否正常
//try
//{
// TcpClient mail = new TcpClient();
// SslStream sslStream;
// mail.Connect(serveraddress, port);
// sslStream = new SslStream(mail.GetStream());
// sslStream.AuthenticateAsClient(serveraddress);
// bool flag = sslStream.IsAuthenticated;
// if (!flag)
// {
// throw new Exception("sslstream IsAuthenticated return false");
// }
//}
//catch (Exception ex)
//{
// throw ex;
//}
string account = "zxd***@qq.com";
string passWord = "**********";//获得的授权码
handler.RecordError("开始收取邮件");
//准备工作结束
ImapClient client = new ImapClient();
#region 连接到邮件服务器
try
{
//一、创建获取邮件客户端并连接到邮件服务器。
//带端口号和协议的连接方式
client.Connect(serveraddress, port, true);
}
catch (ImapCommandException ex)
{
handler.RecordError($"---------尝试连接时出错:{0}------------" + ex.Message);
}
catch (ImapProtocolException ex)
{
handler.RecordError($"---------尝试连接时的协议错误:{0}------------" + ex.Message);
}
catch (Exception ex)
{
handler.RecordError($"---------服务器连接错误:{0}------------" + ex.Message);
}
try
{
// 二、验证登录信息,输入账号和密码登录。
client.Authenticate(account, passWord);
}
catch (AuthenticationException ex)
{
handler.RecordError($"---------无效的用户名或密码:{0}------------" + ex.Message);
}
catch (ImapCommandException ex)
{
handler.RecordError($"---------尝试验证错误:{0}------------" + ex.Message);
}
catch (ImapProtocolException ex)
{
handler.RecordError($"---------尝试验证时的协议错误:{0}------------" + ex.Message);
}
catch (Exception ex)
{
handler.RecordError($"---------账户认证错误:{0}------------" + ex.Message);
}
#endregion
// 三、获取邮箱文件夹。这次用到的的收件箱文件夹叫Test。
//获取所有的文件夹
//List<IMailFolder> mailFolderList = client.GetFolders(client.PersonalNamespaces[0]).ToList();
//只获取收件箱文件夹
//var folder = client.GetFolder("其他文件夹/Test");
var folder = client.GetFolder("INBOX");
//四、从文件夹获取文件
//打开文件夹并设置为读的方式
folder.Open(MailKit.FolderAccess.ReadOnly);
//获取大于2022-06-17时间的所有邮件的唯一Id
var uidss = folder.Search(SearchQuery.DeliveredAfter(DateTime.Parse("2022-06-17")));
//获取邮件头
var MailHeaders = folder.Fetch(uidss, MessageSummaryItems.UniqueId | MessageSummaryItems.Full);
//同主题邮件取日期最新
var NeedMailIds = from a in MailHeaders
group a by a.NormalizedSubject into grp
let maxTime = grp.Max(a => a.Date.DateTime)
from row in grp
where row.Date.DateTime == maxTime
select row.UniqueId;
int b = 0;
string[] sublist = new string[NeedMailIds.Count()];
if (NeedMailIds != null)
{
//获取邮件信息
foreach (var item in NeedMailIds)
{
MimeMessage message = folder.GetMessage(item);
sublist[b] = message.Subject;
////提取该邮件所有普通附件
//foreach (MimePart attachment in message.Attachments)
//{
// //下载附件
// using (var cancel = new System.Threading.CancellationTokenSource())
// {
// string filePath = Path.Combine(outDirPath, attachment.FileName);
// using (var stream = File.Create(filePath))
// {
// attachment.ContentObject.DecodeTo(stream, cancel.Token);
// }
// }
//}
b++;
}
}
//关闭文件夹
folder.Close();
}
//连接gmail的测试
//static void Connect()
//{
// TcpClient mail = new TcpClient();
// SslStream sslStream;
// int bytes = -1;
// mail.Connect("pop.gmail.com", 995);
// sslStream = new SslStream(mail.GetStream());
// sslStream.AuthenticateAsClient("pop.gmail.com");
// byte[] buffer = new byte[2048];
// // Read the stream to make sure we are connected
// bytes = sslStream.Read(buffer, 0, buffer.Length);
// Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
// //Send the users login details
// sslStream.Write(Encoding.ASCII.GetBytes("USER USER_EMAIL\r\n"));
// bytes = sslStream.Read(buffer, 0, buffer.Length);
// Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
// //Send the password
// sslStream.Write(Encoding.ASCII.GetBytes("PASS USER_PASSWORD\r\n"));
// bytes = sslStream.Read(buffer, 0, buffer.Length);
// Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
// // Get the first email
// sslStream.Write(Encoding.ASCII.GetBytes("RETR 1\r\n"));
// bytes = sslStream.Read(buffer, 0, buffer.Length);
// Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
//}
//private static void ImapSearchEmail(EmailAcount emailAcount)
//{
// using (Imap imap = new Imap())
// {
// try
// {
// imap.Connect("imap.qq.com"); // or ConnectSSL for SSL
// imap.UseBestLogin(用户名、密码);
// imap.SelectInbox();
// List<long> uids = imap.Search(Expression.Since(Convert.ToDateTime(DateTime.Now.ToShortDateString())));
// uids.ForEach(u =>
// {
// //邮件对象
// var email = new MailBuilder().CreateFromEml(imap.GetMessageByUID(u));
// });
// }
// catch (Exception ex)
// {
// //异常日志
// }
// finally
// {
// imap.Close();
// }
// }
//}
}
}