I have moved somethings around and inline images are handled better. no solution to adding the mails file attachments (not inline) to the onenote page as an attached file (one:inserted file?)
await Task.Run(() =>
{
string subject = mailItem.Subject;
string from = mailItem.SenderName;
string to = mailItem.To;
string cc = mailItem.CC;
DateTime sentTime = mailItem.SentOn;
string attachments = string.Empty;
string insertedFiles = string.Empty;
string emailBody =
"<table border=\"1\" cellpadding=\"5\"><tr><th>Subject</th><th>From</th><th>To</th><th>CC</th><th>Sent Time</th><th>Attachments</th></tr>" +
$"<tr><td>{subject}</td><td>{from}</td><td>{to}</td><td>{cc}</td><td>{sentTime}</td><td>{insertedFiles}</td></tr></table>" +
mailItem.HTMLBody;
List<string> attachmentPaths = new List<string>();
foreach (Outlook.Attachment attachment in mailItem.Attachments)
{
bool isInline = false;
try
{
isInline = (bool)attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x7FFE000B");
}
catch (Exception)
{
}
if (!isInline)
{
//what to do here!!!!
}
else if (isInline)
{
byte[] attachmentData = (byte[])attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37010102");
// Convert the binary data to a base64 string
string base64String = Convert.ToBase64String(attachmentData);
// Replace the inline image tag with the base64 encoded string
string cid = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E") as string;
emailBody = emailBody.Replace($"cid:{cid}", $"data:image/png;base64,{base64String}");
}
}
// Create new OneNote page and insert email content
string xmlHierarchy;
onenoteApp.GetHierarchy("", HierarchyScope.hsSections, out xmlHierarchy);
string targetID = string.Empty;
onenoteApp.OpenHierarchy(targetPath, string.Empty, out targetID);
onenoteApp.CreateNewPage(targetID, out string pageID, NewPageStyle.npsBlankPageWithTitle);
int outlineID = new Random().Next();
string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, m_outlineIDMetaName);
string xml = string.Format(m_xmlNewOutline, outlineContent, pageID, m_xmlns);
// Get the title and set it to our page name
onenoteApp.GetPageContent(pageID, out xml, PageInfo.piAll);
XNamespace ns = null;
var doc = XDocument.Parse(xml);
ns = doc.Root.Name.Namespace;
var title = doc.Descendants(ns + "T").First();
title.Value = subject;
// Update the page to add pagetitle/pagename
onenoteApp.UpdatePageContent(doc.ToString());
outlineContent = string.Format(m_xmlNewOutlineContent,emailBody, outlineID, m_outlineIDMetaName);
xml = string.Format(m_xmlNewOutline, outlineContent, pageID, m_xmlns);
// Update the page again to add the actual body of the mailitem
onenoteApp.UpdatePageContent(xml, DateTime.MinValue);
});