首页 > 解决方案 > 无法将附件添加到 C# 电子邮件

问题描述

我似乎很难让以下代码正常工作。如果我使用下面的代码,它表明该文件不存在,即使它刚刚创建(我可以在 explorer.xml 中看到它)。

string path = @"LicenceFile.stslic";
File.WriteAllText(path, LicenceKey.ToString() + ";" + CRCValue + ";" + dateExpiry.Value.ToString("dd MMMM yyyy") );

Outlook.Application _app = new Outlook.Application();
Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
mail.To = txtEmail.Text;

mail.Subject = "Your System Licence Key";
mail.Body = "Hello " + Environment.NewLine + Environment.NewLine + "Please find attached your most recent licencing file for the use of the system." + Environment.NewLine + "Please tranfer this file to one of the STS machines." + Environment.NewLine + "Please double click on this file which should then return if the file has been installed succesfully." + Environment.NewLine + Environment.NewLine + "Many Thanks" + Environment.NewLine + Environment.NewLine + "Me";
mail.Importance = Outlook.OlImportance.olImportanceHigh;
mail.ReadReceiptRequested = true;
mail.Attachments.Add((path));

((Outlook._MailItem)mail).Send();

标签: c#outlook

解决方案


mail.Attachments.Add() 方法有四个参数,可以参考下面的代码。

mail.Attachments.Add(path, Outlook.OlAttachmentType.olByValue, 1, path);

path 参数可以是一个文件(由带有文件名的完整文件系统路径表示)或构成附件的 Outlook 项目。可以参考以下代码示例

string path = @"C:\Users\v-zhzhen\Desktop\study notes\exchange.docx";
            string str = "sadie@contoso.com";
            Outlook.Application _app = new Outlook.Application();
            Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
            mail.Subject = "Your System Licence Key";
            mail.Body = "Hello " + Environment.NewLine + Environment.NewLine + "Please find attached your most recent licencing file for the use of the system." + Environment.NewLine + "Please tranfer this file to one of the STS machines." + Environment.NewLine + "Please double click on this file which should then return if the file has been installed succesfully." + Environment.NewLine + Environment.NewLine + "Many Thanks" + Environment.NewLine + Environment.NewLine + "Me";
            mail.Importance = Outlook.OlImportance.olImportanceHigh;
            mail.ReadReceiptRequested = true;
            MessageBox.Show(path);
            if (path.Length > 0)
            {
                mail.Attachments.Add(path, Outlook.OlAttachmentType.olByValue, 1, path);
            }
            mail.To = str;
            mail.Display();
            ((Outlook._MailItem)mail).Send();

推荐阅读