我在Visual中使用VB.NET构建了一个应用程序,它从Outlook邮箱中提取邮件消息,并将消息信息保存到数据库中,并将附件(如果有的话)下载到文件夹中。在将邮件消息保存到我的数据库之前,如果消息来自某个用户,则将消息转发到另一个邮箱(因此,我不保存消息)。这一切都很好,除非我试图转发一条带有附件的消息。
正如标题中所述,我使用OpenPOP来提取邮件,使用SMTP传输邮件。当我尝试从OpenPOP消息创建SMTP附件时,我会得到以下错误:
System.InvalidCastException:将“MessagePart”类型转换为“String”类型无效。
消息在行的AddAttachments函数中抛出(如下):
myAttachment =新附件(附件)(在每个语句中)
Public Sub ForwardMessage(
ByVal msgPOP As OpenPop.Mime.Message,
toAddress As String,
fromAddress As String,
subject As String,
body As String
)
Dim smtpServer As New System.Net.Mail.SmtpClient(Me.serverName)
Dim msgSMTP As New MailMessage()
msgSMTP.Sender = New MailAddress(fromAddress)
msgSMTP.To.Add(New MailAddress(toAddress))
msgSMTP.Subject = subject
msgSMTP.Body = body
msgSMTP.IsBodyHtml = True
Dim attachments As Object
attachments = AddAttachments(msgPOP, msgSMTP)
msgSMTP.Attachments.Add(New Attachment(attachments))
smtpServer.Send(msgSMTP)
End Sub,在朋友的帮助下,我终于想出了答案。下面的AddAttachments函数已被编辑,以显示修复.
Public Function AddAttachments(
ByVal msgPOP As OpenPop.Mime.Message,
ByVal msgSMTP As MailMessage
) As MailMessage
Dim attachments As Object = msgPOP.FindAllAttachments()
Dim myAttachment As Attachment = Nothing
For Each attachment As OpenPop.Mime.MessagePart In attachments
Dim sName As String = attachment.FileName
Dim sContentType As String = attachment.ContentType.MediaType
Dim stream As MemoryStream = New MemoryStream(attachment.Body)
myAttachment = New Attachment(stream, sName, sContentType)
msgSMTP.Attachments.Add(myAttachment)
Next
Return msgSMTP
End Function我花了几个小时研究这个问题,还没有找到一个解决办法。我试图将应用程序数据类型更改为String,而将OpenPOP.MIME.MessagePart更改为无效。我尝试在附件变量中添加"ToString“,并收到以下错误:
System.InvalidCaseException:运算符'&‘未为'MessagePart’和字符串“.ToString”定义。
我一直在阅读默剧,看看这是否会提供一些想法,虽然我还没有能够连接到点。我假设这是可能的,并希望有人能够分享解决方案,我对VB.NET或C#.NET都会很满意。
非常感谢您的提前,我很感谢您的时间。
发布于 2020-03-30 18:41:40
解决方案在我上面的文章中编辑的AddAttachments函数中。
https://stackoverflow.com/questions/60746074
复制相似问题