C# Adding a file (pdf,word, ect..) to a onenote page as Attach File

dimitry okken 0 Reputation points
2023-04-06T17:46:47.9366667+00:00

I am trying to make sort of a outlook "send to onenote" plugin (as a drag and drop) in my .net 6.0 winform c# app. i am as far that the entire body of the email (dragged from 1 of 2 listviews that reads outlook inbox and outbox) is pushed to onenote as a new page (listviewArchive holds folders that contain .one section files). the only problem is that I can not seem to figure out how to add the attachments (not inline,but files as attachments in mailitem) to the onennote page the same way the outlook "sent to onenote" plugin does it SendToOnenote_plugin

and this is how my code creates something similar
MyMethod

the code I am using to push the email to onenote is


using Onenote = Microsoft.Office.Interop.OneNote;

private async void listViewArchive_DragDrop(object sender, DragEventArgs e)
        {
            Point clientPoint = listViewArchive.PointToClient(new Point(e.X, e.Y));
            ListViewItem targetItem = listViewArchive.GetItemAt(clientPoint.X, clientPoint.Y);

            Onenote.Application onenoteApp = new Onenote.Application();

            if (targetItem != null && e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection)))
            {
                ViewReadOnly = false;

                string targetPath = (string)targetItem.Tag;
                string folderName = draggedFrom ? "in.one" : "out.one";

                targetPath = Path.Combine(targetPath, folderName);

                if (!File.Exists(targetPath))
                {
                    MessageBox.Show("No section file found, Mailwill not be added as a page", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    Marshal.ReleaseComObject(onenoteApp);       
                    onenoteApp= null;
                    return;
                }

                ListView.SelectedListViewItemCollection selectedItems = (ListView.SelectedListViewItemCollection)e.Data.GetData(typeof(ListView.SelectedListViewItemCollection));

                foreach (ListViewItem item in selectedItems)
                {

                    if (item.Tag is Outlook.MailItem mailItem)
                    {

                        string m_xmlNewOutlineContent =
                        "<one:Meta name=\"{2}\" content=\"{1}\"/>" +
                        "<one:OEChildren><one:HTMLBlock><one:Data><![CDATA[{0}]]></one:Data></one:HTMLBlock></one:OEChildren>";

                        string m_xmlNewOutline =
                        "<?xml version=\"1.0\"?>" +
                        "<one:Page xmlns:one=\"{2}\" ID=\"{1}\">" +
                        "<one:Outline>{0}</one:Outline></one:Page>";

                        string m_outlineIDMetaName = "Outlook Email To OneNote AddIn ID";

                        string m_xmlns = "http://schemas.microsoft.com/office/onenote/2013/onenote";

                        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 = "";

                            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)
                                {
                                    // still to add....
                                }

                                if (!isInline)
                                {
                                    string attachmentPath = Path.Combine(Path.GetTempPath(), attachment.FileName);
                                    attachment.SaveAsFile(attachmentPath);
                                    attachmentPaths.Add(attachmentPath);
                                    attachments += attachment.FileName + ";";
                                }
                            }

                            string insertedFiles = string.Empty;
                            foreach (string attachmentPath in attachmentPaths)
                            {
                             //code to add the files to the table in string emailBody, no idea how....
                            }
                            
                            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;

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

                            // Update the page again to add the actual body of the mailitem
                            onenoteApp.UpdatePageContent(xml, DateTime.MinValue);
                        });      
                    }
                }
            }

            Marshal.ReleaseComObject(onenoteApp);       
            onenoteApp= null;
        }

it handles inline image not always correctly to. Took me a lot of internet searches and copy/paste to get to this piont but... if anybody could add to the code to handle the attachments and maybe look at inline images that are in the mailitem's body, that would be great! I do not have enough knowledge to figure this one out.... did a lot but did not keep this. and got lost. search alot in stackoverflow but could not find anything for this...

OneNote
OneNote
A family of Microsoft products that enable users to capture, organize, and reuse notes electronically.
178 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,609 questions
Outlook
Outlook
A family of Microsoft email and calendar products.
3,397 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,616 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. dimitry okken 0 Reputation points
    2023-04-11T13:29:52.86+00:00

    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);
    
                            });
    
    0 comments No comments