本文主要談談實現思路,不提供完整代碼
一、分離基礎
1.MIME郵件的multipart類型
引用文章:https://blog.csdn.net/wangyu13476969128/article/details/72724179
MIME,英文全稱為"Multipurpose Internet Mail Extensions",即多用途互聯網郵件擴展,是目前互聯網電子郵件普通遵循的技術規則。
郵件體包含郵件的內容, 它的類型由郵件頭的“Content-Type”域指出。常見的簡單類型有text/plain(純文本)和text/html(超文本)。
MIME郵件Content-Type域常見的主類型如下:
主類型 | 常見屬性 | 參數含義 |
---|---|---|
text | charset | 文本信息所使用的字符集 |
image | name | 圖像的名稱應用程序的名稱 |
application | name | 應用程序的名稱 |
multipart | boundary | 郵件分段邊界標識 |
對於multipart類型,下面有三種子類型:mixed、alternative、related
multipart/mixed可以包含附件。
multipart/related可以包含內嵌資源。
multipart/alternative 純文本與超文本共存
二、附件分離
引用文章:C#使用MailKit獲取郵件中的附件(QQ郵箱/163網易郵箱)
1.保存附件
通過獲取到的MimeMessage可以輕松得到附件,注意超過50M的文件為超大附件,不能下載,如qq的處理是將發一個鏈接提供下載。
/// <summary>
/// 獲取郵件的附件
/// </summary>
/// <param name="attachments"></param>
/// <param name="messageId"></param>
/// <returns></returns>
public List<EmailAttachmentDto> GetEmailAttachments(IEnumerable<MimeEntity> attachments, string messageId)
{
var emailAttachments = new List<EmailAttachmentDto>();
foreach (var attachment in attachments)
{
if (attachment.IsAttachment)
{
var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
var filePath = MailHelper.GetEmlAttachmentFilePath(fileName, messageId);
using (var stream = File.Create(filePath))
{
if (attachment is MessagePart rfc822)
{
rfc822.Message.WriteTo(stream);
}
else
{
var part = (MimePart)attachment;
part.Content.DecodeTo(stream);
}
}
var mailFileInfo = new FileInfo(filePath);
emailAttachments.Add(new EmailAttachmentDto() { FilePath = filePath, FileName = fileName, FileSize = mailFileInfo.Length });
}
}
return emailAttachments;
}
2.保存EML
其實,這一步才是關鍵,移除附件,只保存其他內容到eml,這樣才不會讀取時由於文件太大導致卡死
if (mimeMessage.Body is Multipart multipart)
{
while (mimeMessage.Attachments.Any())
{
multipart.Remove(mimeMessage.Attachments.ElementAt(0));
}
var mineMessage = new MimeMessage()
{
Sender = mimeMessage.Sender,
Body = multipart,
MessageId = customerMimeMessage.Id.ToString(),
};
if (!System.IO.File.Exists(fileName))
{
await mineMessage.WriteToAsync(fileName);
}
}
這樣就完成了,附件和郵件eml分開存儲
參考文章
http://www.it1352.com/675410.html
https://www.cnblogs.com/pengze0902/p/8519715.html
https://www.cnblogs.com/rocketRobin/p/8337055.html