我已经尝试了此网站上提供的许多解决方案来将文件附加到电子邮件,但无论我尝试什么,我总是在所在行收到“抱歉,出了点问题。您可能想重试”消息我尝试将该文件附加到我的 Outlook 邮件项目中。
try
{
App = new Microsoft.Office.Interop.Outlook.Application();
MailItem mailItem = App.CreateItem(OlItemType.olMailItem);
mailItem.Subject = Subject;
mailItem.To = To;
mailItem.CC = CC;
mailItem.BCC = BCC;
mailItem.Body = Body;
// make sure a filename was passed
if (string.IsNullOrEmpty(FileAtachment) == false)
{
// need to check to see if file exists before we attach !
if (!File.Exists(FileAtachment))
MessageBox.Show("Attached document " + FileAtachment + " does not exist", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(FileAtachment);
mailItem.Attachments.Add(attachment, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
}
}
mailItem.Display(); // display the email
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
任何人都可以提供任何想法如何让它发挥作用吗?我可以毫无问题地发送电子邮件,但是当我尝试添加附件时,它不起作用:(
Attachments.Add 方法接受一个文件(由带有文件名的完整文件系统路径表示)或构成附件的 Outlook 项目,但不接受附件对象:
App = new Microsoft.Office.Interop.Outlook.Application();
MailItem mailItem = App.CreateItem(OlItemType.olMailItem);
mailItem.Subject = Subject;
mailItem.To = To;
mailItem.CC = CC;
mailItem.BCC = BCC;
mailItem.Body = Body;
// make sure a filename was passed
if (string.IsNullOrEmpty(FileAtachment) == false)
{
// need to check to see if file exists before we attach !
if (!File.Exists(FileAtachment))
MessageBox.Show("Attached document " + FileAtachment + " does not exist", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
Attachment attachment = mailItem.Attachments.Add("D:\\text.txt", Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
}
}
mailItem.Display(); // display the email
我使用的是 Outlook 2016,对我来说,在添加附件之前显示邮件就可以了(只要附件是有效的文件路径)
App = new Microsoft.Office.Interop.Outlook.Application();
MailItem mailItem = App.CreateItem(OlItemType.olMailItem);
mailItem.Subject = Subject;
mailItem.To = To;
mailItem.CC = CC;
mailItem.BCC = BCC;
mailItem.Body = Body;
// display the item before adding the attachments
mailItem.Display(); // display the email
// make sure a filename was passed
if (string.IsNullOrEmpty(FileAtachment) == false)
{
// need to check to see if file exists before we attach !
if (!File.Exists(FileAtachment))
MessageBox.Show("Attached document " + FileAtachment + " does not exist", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
Attachment attachment = mailItem.Attachments.Add("D:\\text.txt", Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
}
}
Attachments.Add 需要一个字符串作为参数。该字符串必须是您尝试附加的文件的完全限定名称。
将流保存到临时文件,将文件名传递给 Attachments.Add,删除文件。