将OpenPOP附件转发到SMTP(System.Net.Mail)



我在Visual Studio中使用VB.NET构建了一个应用程序,该应用程序从Outlook邮箱提取邮件,将邮件信息保存到数据库中,并将附件(如果有(下载到文件夹中将邮件保存到我的数据库之前,如果邮件来自某个用户,我会将邮件转发到另一个邮箱(因此,我不会保存邮件(。这一切都很好,除了当我尝试转发带有附件的邮件时。

正如标题中所述,我正在使用OpenPOP拉取邮件,并使用SMTP传输邮件。当我尝试从OpenPOP消息创建SMTP附件时,我收到以下错误:

System.InvalidCastException:从类型"MessagePart"到类型"String"的转换无效

消息在AddAttachments函数(下面(的行中抛出:

myAttachment=新附件(附件((在For Each语句中(

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

我花了几个小时研究这个问题,但我还没有找到一个解决方案。我尝试将应用程序数据类型更改为字符串OpenPOP.MIME.MessagePart,但没有成功。我尝试将"ToString"添加到附件变量中,并收到以下错误:

System.InvalidCaseException:运算符'&'未为类型"MessagePart"和字符串".ToString"定义。

我一直在阅读MIME,看看它是否能提供一些想法,尽管我无法连接这些点。我认为这是可能的,希望有人能够分享解决方案,我会对VB.NET或C#.NET.感到满意

事先非常感谢,非常感谢您抽出时间。

解决方案在我上面的原始文章中编辑的AddAttachments函数中。

相关内容

  • 没有找到相关文章

最新更新