我创建了一个代码,它构建了一个作为电子邮件正文的 html 字符串。但是,我希望这封电子邮件成为我最初创建的常规电子邮件和基本电子邮件的附件。下面的代码实际上是有效的,但最后,当我打开我的普通电子邮件时,我有辅助电子邮件作为附件,但是当我点击它时,附加的电子邮件是一封空白电子邮件。尽管我创建了 html 正文,但这个结果。html 字符串在最后一个方法“AddMessageAsAttachment”的末尾消失了。任何帮助将不胜感激......谢谢
using Microsoft.Office.Interop.Outlook;
foreach (var positionlist in result)
{
string salesEmailAddress = positionlist.Key;
//Create the general email to the salesman
Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Application();
MailItem generalMail = application.CreateItem(Outlook.OlItemType.olMailItem) as MailItem;
generalMail.Body = "Hello, Please find your quarterly reports";
generalMail.Subject = $"Quarterly Report";
generalMail.To = salesEmailAddress;
foreach (DataRow row in positionlist)
{
MailItem mailToAdd = CreateSecondaryEmail(row, "EN", "P:/My_path/Report_EN.oft", @"P:\Another_path\SecondaryEmailAttachment.pdf");
Globale.AddMessageAsAttachment(generalMail, mailToAdd);
}
private MailItem CreateSecondaryEmail(DataRow row, string lang, string template, string attachement)
{
string clientNumber = row["account_nbr"];
string currency = row["Ccy"];
html += $@"<html>
<div style='font-family: Haboro Contrast Ext Thin;font-size: 15,5'>
<p style=''></p><BR>
<span style=''>{clientNumber}</span><BR>
<span style=''> {currency}</span><BR>
</div>";
html += "</html>";
MailItem mailPosition = Globale.CreateItemFromTemplate(html, email, template, factsheet);
return mailPosition;
}
}
“CreateItemFromTemplate”实际上从模板链接到辅助电子邮件的正文和将附加的快速 pdf 报告(参数“附件”):
public static Outlook.MailItem CreateItemFromTemplate(string html, string emailaddress, string template, string attachement = null, string client_number = null)
{
Outlook.Application application = new Outlook.Application();
Outlook.MailItem mail = application.CreateItemFromTemplate(template) as Outlook.MailItem;
mail.HTMLBody = mail.HTMLBody.Replace("#BODY", html);
DateTime dt = DateTime.Now;
string date = $"Data as of {dt.Day}.{dt.Month}.{dt.Year}";
mail.HTMLBody = mail.HTMLBody.Replace("#DATE",date);
mail.Subject = $"Quarterly Report of the client {client_number}";
mail.To = emailaddress;
if (attachement != null)
{
mail.Attachments.Add(attachement);
}
return mail;
}
最终,我创建了一个“Globale”类,该类将检索由上述“CreateItemFromTemplate”方法生成的辅助电子邮件(mailPosition)并将其作为附件放入普通电子邮件中。
public static void AddMessageAsAttachment(Outlook.MailItem mailContainer,Outlook.MailItem mailToAttach)
{
Outlook.Attachments attachments = null;
Outlook.Attachment attachment = null;
try
{
attachments = mailContainer.Attachments;
attachment = attachments.Add(mailToAttach,
Outlook.OlAttachmentType.olEmbeddeditem, 1, "The attached e-mail");
mailContainer.Save();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
if (attachment != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(attachment);
if (attachments != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(attachments);
}
}