我花了 3 天时间尝试从已签名但未加密的电子邮件中提取附件。我们的项目在 vb.net 中,但应该很容易将其重写为 c#。以下是对我有用的步骤:
- 安装Mimekit Nuget 包
- 通过查看其内容类型和附件名称来正确识别 S/Mime 签名的电子邮件(S/Mime 签名的电子邮件始终附有 smime.p7m 文件)
If String.Equals(origMessage.Attachments.First.ContentType, "multipart/signed",
StringComparison.OrdinalIgnoreCase) AndAlso
String.Equals(origMessage.Attachments.First.Name, "smime.p7m", StringComparison.OrdinalIgnoreCase) Then
- 将 smime 文件加载为 EWS FileAttachment 并从中创建新的 memoryStream。然后创建此流的 MimeKit.MimeEntity。现在你正在使用非常适合这些东西的 MimeKit 库
Dim smimeFile As FileAttachment = origMessage.Attachments.First
smimeFile.Load()
Dim memoryStreamSigned As MemoryStream = New MemoryStream(smimeFile.Content)
Dim entity = MimeEntity.Load(memoryStreamSigned)
- 遍历所有附件的 MimeEntity 实例
If TypeOf entity Is Cryptography.MultipartSigned Then
Dim mltipart As Multipart = entity
Dim attachments As MimeEntity = mltipart(0)
If TypeOf attachments Is Multipart Then
Dim mltipartAttachments As Multipart = attachments
For i As Integer = 0 To mltipartAttachments.Count - 1
If mltipartAttachments(i).IsAttachment Then
**'BOOM, now you're looping your attachment files one by one**
**'Call your decode function to read your attachment as array of Bytes**
End If
Next
End If
End If
- 将您的附件读取为字节数组。在上一步的 for 中执行此操作。
'Read and decode content stream
Dim fileStrm = New MemoryStream()
mltipartAttachments(i).Content.DecodeTo(fileStrm)
Dim decodedBytes(0 To fileStrm.Length - 1) As Byte
fileStrm.Position = 0 'This is important because .DecodeTo set the position to the end!!
fileStrm.Read(decodedBytes, 0, Convert.ToInt32(fileStrm.Length))
现在您将附件文件解码为字节数组,您可以保存它或做任何您想做的事情:)希望这会有所帮助!