vb.net 使用 smtp 和 outlook.CreateItemFromTemplate 发送 outlook 电子邮件

vb.net send outlook email using smtp and outlook.CreateItemFromTemplate

我想使用 SMTP 服务器和 Outlook 模板发送电子邮件作为邮件消息。

Dim application As New Outlook.Application
Dim path As String = "S:\TCM\Vendor.oft"

' Create a new MailItem and set the To, Subject, and Body properties.
Dim newMail As Outlook.MailItem = DirectCast(application.CreateItemFromTemplate(path), Outlook.MailItem)

Dim mail As MailMessage = DirectCast(newMail, MailMessage)

我正在尝试从模板创建邮件项目并将其转换为 MailMessage,以便我可以使用 SMTP 服务器发送电子邮件。但是,我收到以下错误。

Unable to cast COM object of type 'System.__ComObject' to class type 'System.Net.Mail.MailMessage'.

Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.

Outlook.MailItem 显然对 System.Net.Mail.MailMessage 对象一无所知。

您有责任将 Outlook 邮件转换为 MIME 邮件and/or在发送之前显式填充所有 MailMessage 属性。

BCL 的 MailMessage 和 Outlook 的 MailItem 之间没有直接转换。您可以通过设置 SendUsingAccount 属性 从 Outlook 中的不同帐户发送 MailItem,它允许设置一个帐户对象,代表要发送 MailItem 的帐户。

您可能会发现 How To: Create and send an Outlook message programmatically 文章很有帮助。