如何从模板创建电子邮件

问题描述 投票:0回答:1

我正在尝试打开电子邮件模板 (

.msg
) 进行编辑,但在尝试打开模板后代码不断“捕获”。

我不断收到此错误

抛出异常:Estimator.exe 中的“System.InvalidCastException”

这是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;
using System.Drawing.Text;

// Create emails
Outlook.Application outlookApp = InitializeOutlook();
string msgPath = @"C:\Users\andyk\OneDrive\Projects\Visual Studio\Estimator\files\Template.msg";

try
{
    // Open template
    Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.Session.OpenSharedItem(msgPath);
    mailItem.Display();
}
catch (Exception ex)
{
    Console.WriteLine($"Error opening template: {ex.Message}");
}
finally
{
    // Clean up COM objects
    Marshal.ReleaseComObject(outlookApp);
}
c# email outlook
1个回答
0
投票

这很可能意味着 MSG 文件不是

MailItem
。可以是别的东西吗?接触?预约?任务?

将该行更改为

dynamic mailItem = outlookApp.Session.OpenSharedItem(msgPath);
MsgBox(mailIten.Class);

并确保您得到 43(即

OlObjectClass.olMail

© www.soinside.com 2019 - 2024. All rights reserved.