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

Forwarding OpenPOP Attachments to SMTP (System.Net.Mail)

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

如题所述,我是用OpenPOP拉取邮件,用SMTP传输邮件。当我尝试从 OpenPOP 邮件创建 SMTP 附件时,出现以下错误:

System.InvalidCastException: Conversion from type 'MessagePart' to type 'String' is not valid.

消息在 AddAttachments 函数(下)中抛出:

myAttachment = New Attachment(attachment) (in the For Each statement)

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

我花了几个小时研究这个问题,但我还没有找到解决方案。我尝试将 application 数据类型更改为 StringOpenPOP.MIME.MessagePart 无济于事。我尝试将 "ToString" 添加到 attachment 变量并收到以下错误:

System.InvalidCaseException: Operator '&' is not defined for type 'MessagePart' and string ".ToString".

我一直在阅读有关 MIME 的文章,看看它是否能提供一些想法,尽管我无法将这些点联系起来。我假设这是可能的,希望有人能够分享解决方案,我会对 VB.NET 或 C#.NET 感到满意。

非常感谢您的宝贵时间。

解决方法在上面我原来的 post 中编辑的 AddAttachments 函数中。