You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

259 lines
11 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using MailKit;
using MailKit.Net.Imap;
using MailKit.Search;
using MailKit.Security;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;
using Common.Extensions;
namespace Common.Tools.Email
{
/// <summary>
/// 邮件接收Help
/// </summary>
public class MailReceiveHelper
{
///// <summary>
///// 设置设置收件人信息
///// </summary>
///// <returns></returns>
//public static SendServerConfigurationEntity SetSendMessage()
//{
// var sendServerConfiguration = new SendServerConfigurationEntity
// {
// SmtpHost = ConfigurationManager.AppSettings["SmtpServer"],
// SmtpPort = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]),
// IsSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["IsSsl"]),
// MailEncoding = ConfigurationManager.AppSettings["MailEncoding"],
// SenderAccount = ConfigurationManager.AppSettings["SenderAccount"],
// SenderPassword = ConfigurationManager.AppSettings["SenderPassword"]
// };
// return sendServerConfiguration;
//}
/// <summary>
/// 接收符号条件的Email 队列
/// </summary>
/// <param name="sendServerConfiguration">收件人Email配置信息</param>
/// <param name="searchQuery">接收邮件的条件 示例 SearchQuery.SubjectContains("MimeKit").Or(SearchQuery.SubjectContains("MailKit")).Or(SearchQuery.DeliveredAfter(DateTime.Parse("2016-9-1")))</param>
/// <param name="MailIdList">如果有EailID 这是读取Email数据 则searchQuery 失效</param>
/// <param name="PartPath">附件的保存地址 有指定则保存附件 MailIdList不为空的清空下</param>
/// <returns></returns>
public static List<MailBodyEntity> ReceiveEmailHead(SendServerConfigurationEntity sendServerConfiguration, SearchQuery searchQuery=null,long[] MailIdList=null,string PartPath=null)
{
var getlist = new List<MailBodyEntity>();
try
{
if (sendServerConfiguration == null)
{
throw new ArgumentNullException();
}
// using (var client = new ImapClient(new ProtocolLogger(MailMessage.CreateMailLog())))
using (var client = new ImapClient())
{
if (sendServerConfiguration.IsSsl)
{
client.Connect(sendServerConfiguration.SmtpHost, sendServerConfiguration.SmtpPort, SecureSocketOptions.SslOnConnect);
}
else
{
client.Connect(sendServerConfiguration.SmtpHost, sendServerConfiguration.SmtpPort, SecureSocketOptions.None);
}
client.Authenticate(sendServerConfiguration.SenderAccount, sendServerConfiguration.SenderPassword);
client.Inbox.Open(FolderAccess.ReadOnly);
if (MailIdList == null)
{
if (searchQuery == null) {
searchQuery = SearchQuery.All;
}
var uids = client.Inbox.Search(searchQuery);
var items = client.Inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.All);
foreach (var uid in items)
{
var newhead = new MailBodyEntity
{
UniqueId = uid.UniqueId.Id,
Subject = uid.Envelope.Subject
,
SendTime = uid.Date.DateTime.ToTimeStamp()
};
foreach (var from in uid.Envelope.From)
{
newhead.Sender += "," + from.GetType().GetProperty("Address").GetValue(from).ToString();
}
if (newhead.Sender.IsNotNull())
{
newhead.Sender = newhead.Sender.Substring(1, newhead.Sender.Length - 1);
}
getlist.Add(newhead);
}
}
else if (MailIdList.Length > 0) {
var udilist = new List<UniqueId>();
foreach (var id in MailIdList) {
var newuid = new UniqueId((uint)id);
udilist.Add(newuid);
}
foreach (var uid in udilist) {
var message = client.Inbox.GetMessage(uid);
var newmailbody = new MailBodyEntity
{
UniqueId = uid.Id,
MessageId=message.MessageId,
Subject = message.Subject
,
SendTime = message.Date.DateTime.ToTimeStamp()
};
newmailbody.MailTextBody = message.HtmlBody;
foreach (var from in message.From)
{
newmailbody.Sender += "," + from.GetType().GetProperty("Address").GetValue(from).ToString();
}
if (newmailbody.Sender.IsNotNull())
{
newmailbody.Sender = newmailbody.Sender.Substring(1, newmailbody.Sender.Length - 1);
}
//保存附件
if (PartPath.IsNotNull()) {
var path = PartPath;
Directory.CreateDirectory(path);
foreach (var file in message.Attachments.OfType<MimePart>()) {
file.FileName = file.FileName.TrimAll();
string filePath = path+"/"+uid.Id.ToString()+"_"+file.FileName;
using (var stream = File.Create(filePath))
{
file.Content.DecodeTo(stream);
}
newmailbody.MailFiles.Add(new MailFile { MailFilePath=filePath,FileName=file.FileName });
}
}
getlist.Add(newmailbody);
}
}
client.Disconnect(true);
}
}
catch(Exception ex){
var msg = ex.Message;
}
return getlist;
}
/// <summary>
/// 接收下载邮件
/// </summary>
/// <param name="sendServerConfiguration">收件人Email配置信息 </param>
/// <param name="searchQuery">示例 SearchQuery.SubjectContains("MimeKit").Or(SearchQuery.SubjectContains("MailKit")).Or(SearchQuery.DeliveredAfter(DateTime.Parse("2016-9-1")))</param>
public static void DownloadBodyParts(SendServerConfigurationEntity sendServerConfiguration, SearchQuery searchQuery)
{
using (var client = new ImapClient())
{
if (sendServerConfiguration.IsSsl)
{
client.Connect(sendServerConfiguration.SmtpHost, sendServerConfiguration.SmtpPort, SecureSocketOptions.SslOnConnect);
}
else
{
client.Connect(sendServerConfiguration.SmtpHost, sendServerConfiguration.SmtpPort, SecureSocketOptions.None);
}
client.Authenticate(sendServerConfiguration.SenderAccount, sendServerConfiguration.SenderPassword);
client.Inbox.Open(FolderAccess.ReadOnly);
// 搜索Subject标题包含“MimeKit”或“MailKit”的邮件
var query = searchQuery;
var uids = client.Inbox.Search(query);
// 获取搜索结果的摘要信息我们需要UID和BODYSTRUCTURE每条消息以便我们可以提取文本正文和附件
var items = client.Inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
foreach (var item in items)
{
// 确定一个目录来保存内容
var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "/MailBody", item.UniqueId.ToString());
Directory.CreateDirectory(directory);
// IMessageSummary.TextBody是一个便利的属性可以为我们找到“文本/纯文本”的正文部分
var bodyPart = item.TextBody;
// 下载'text / plain'正文部分
var body = (TextPart)client.Inbox.GetBodyPart(item.UniqueId, bodyPart);
// TextPart.Text是一个便利的属性它解码内容并将结果转换为我们的字符串
var text = body.Text;
File.WriteAllText(Path.Combine(directory, "body.txt"), text);
// 现在遍历所有附件并将其保存到磁盘
foreach (var attachment in item.Attachments)
{
// 像我们对内容所做的那样下载附件
var entity = client.Inbox.GetBodyPart(item.UniqueId, attachment);
// 附件可以是message / rfc822部件或常规MIME部件
var messagePart = entity as MessagePart;
if (messagePart != null)
{
var rfc822 = messagePart;
var path = Path.Combine(directory, attachment.PartSpecifier + ".eml");
rfc822.Message.WriteTo(path);
}
else
{
var part = (MimePart)entity;
// 注意:这可能是空的,但大多数会指定一个文件名
var fileName = part.FileName;
var path = Path.Combine(directory, fileName);
// decode and save the content to a file
using (var stream = File.Create(path))
part.Content.DecodeTo(stream);
}
}
}
client.Disconnect(true);
}
}
}
}