本文主要談談實現思路,不提供完整代碼html
引用文章:https://blog.csdn.net/wangyu13476969128/article/details/72724179
MIME,英文全稱爲"Multipurpose Internet Mail Extensions",即多用途互聯網郵件擴展,是目前互聯網電子郵件普通遵循的技術規則。
郵件體包含郵件的內容, 它的類型由郵件頭的「Content-Type」域指出。常見的簡單類型有text/plain(純文本)和text/html(超文本)。
MIME郵件Content-Type域常見的主類型以下:app
主類型 | 常見屬性 | 參數含義 |
---|---|---|
text | charset | 文本信息所使用的字符集 |
image | name | 圖像的名稱應用程序的名稱 |
application | name | 應用程序的名稱 |
multipart | boundary | 郵件分段邊界標識 |
對於multipart類型,下面有三種子類型:mixed、alternative、related
multipart/mixed能夠包含附件。
multipart/related能夠包含內嵌資源。
multipart/alternative 純文本與超文本共存.net
引用文章:C#使用MailKit獲取郵件中的附件(QQ郵箱/163網易郵箱)code
經過獲取到的MimeMessage能夠輕鬆獲得附件,注意超過50M的文件爲超大附件,不能下載,如qq的處理是將發一個連接提供下載。htm
/// <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; }
其實,這一步纔是關鍵,移除附件,只保存其餘內容到eml,這樣纔不會讀取時因爲文件太大致使卡死blog
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分開存儲ip
http://www.it1352.com/675410.html
http://www.javashuo.com/article/p-glkusoug-kh.html
http://www.javashuo.com/article/p-fbiswjpv-bv.html資源