无法将附件添加到C#电子邮件

时间:2018-09-03 15:20:47

标签: c# outlook

我似乎在努力使以下代码正常工作。如果我使用下面的代码,则表明该文件即使刚刚创建也不存在(我可以在资源管理器中看到它。

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();

2 个答案:

答案 0 :(得分:0)

请参阅Attachments.Add的文档:

  

Source对象

     

附件的来源。该文件可以是文件(由文件名的完整文件系统路径表示)或构成附件的Outlook项目。

string path = @"LicenceFile.stslic";是相对路径,而不是完整文件系统路径。

答案 1 :(得分:0)

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

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

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();