Issue Using C# to Get RTF Text From Clipboard to Outlook With Formatting and Without Encoding Tags

I have created a little application that gathers data from various text boxes and then combines the data into a formatted richTextBox.  A person using the tool asked if I could then add a button that would allow that text (with formatting) to be copied
and pasted into an Outlook Email.  When I do this, I can get the text into an email, but I either strip out the formatting or I get all the RTF encoding tags to come along with it. 
I have tested to see that the copy of the data from the richTextBox has indeed made it to the clipboard correctly.  This has been verified by the fact that I can manually press "ctrl" + "v" and I can past the text with proper
formatting into the mail body.
I do know that I can brute force things by trying to manually wrap HTML tags around my textBox fields and then pipe that into an HTMLBody property.  In fact I can get a lot of things to work with the HTMLBody property, but while it is nice that will
work, I feel that I must be missing something really simple while trying to work with RTF.
I currently am pasting (using the Clipboard.GetText(TestDataFormat.RTF)) the RTF data into the Body property of the mail item.  This is bringing in all the RTF encoding tags.  I have tried to paste this directly into the RTFBody of the mail item,
yet an execption gets thrown when executed.  Oddly, though, if I change RTFBody to HTMLBody, I do not get the exception, but I still have the RTF encoding tags in it.  Though if I feed the HTMLBody property straight, HTML text with the encoding tags,
it will render properly.
This has me confused then why if I feed HTMLBody HTML text with the encoding tags that it will render, but if I try and do the same for RTFBody and feed it RTF text with encoding tags it still throws an exception.  Any help in the matter would be greatly
appreciated.  I have included the code snippet below for sending the richTextBox information to the clipboard and then attempting to retrieve it and paste it into an Outlook email.
Thanks for the help.
Some pertinent information:
Blend for Visual Studio 2015 CTP6 (I switched from VS2012 as intellisense was added to Blend in 2015)
Because of this Systems.Windows.Forms is not in use
private void buttonEmail_Click(object sender, RoutedEventArgs e)
//Copy richTextBox information to Clipboard
Clipboard.Clear();
richTextBox.SelectAll();
richTextBox.Copy();
//Get current date to add to email subject line
DateTime myNewDate = new DateTime();
myNewDate = DateTime.Now;
//Create Email
Outlook.Application myNewApplication = new Outlook.Application();
Outlook.MailItem myNewMailIoI = myNewApplication.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
myNewMailIoI.To = " "; //An attempt to ensure that the focus moves down to the body field
myNewMailIoI.Subject = "IoI - " + myNewDate.Date.ToString("d");
myNewMailIoI.BodyFormat = Outlook.OlBodyFormat.olFormatRichText;
//Pasting data into body of email
myNewMailIoI.Body = Clipboard.GetText(TextDataFormat.Rtf); //This will past the text with encoding tags into email
//If this section is uncommented, it will add a properly formatted HTML text to the email
//myNewMailIoI.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
//myNewMailIoI.HTMLBody = "<p>This stinks!!!</p>" + "<p style='color: green; font-size:10pt; font-family:arial'>different font and color</p>";
myNewMailIoI.Display(); //Allow for window to be minimized
myNewMailIoI.Display(true);

Ok, I found the solution.  Part of the issue was caused by the confusion of the HTML body property acting as a text encoder for HTML text when a string is passed in vs the RTF Body property needing to have a plain text file taken and encoded into a
byte stream.  Even though the RTF text is in readable text (albeit with the RTF Encoding Tags) it needs to be reencoded into a series of bytes. 
This is where I failed to understand the previous answers.  I knew that RTF Body needed to have a array of bytes, and the previous answers seemed to indicate that the data in the clipboard was already in this byte format (this may have just been my
misunderstanding) and that I needed to somehow take this byte array and do something with it.  My misunderstanding was that all the methods for getting values from the clipboard returned strings and not bytes.
after some digging last night and with the few hints that were offered before, I came across a post on CodeProject (apparently I cannot post links, so I will try and include this so that you can find the postcodeproject(DOTCOM)/Questions/766917/How-to-convert-richtextbox-output-into-bytearray). 
This showed that I needed to take the raw, RTF text with its RTF encoding tags from the clipboard and and encode it to a byte array and then pass this into the RTF Body property.  Included below is the final code such that I hope that it helps some other
person as there seem to be a lot of searches for this on the web, but not a lot of direct answers.
using System.Text;
using Outlook = Microsoft.Office.Interop.Outlook;
private void buttonEmail_Click(object sender, RoutedEventArgs e)
//Copy richTextBox information to Clipboard
Clipboard.Clear();
richTextBox.SelectAll();
richTextBox.Copy();
//Get current date to add to email subject line
DateTime myNewDate = new DateTime();
myNewDate = DateTime.Now;
//Create Email
Outlook.Application myNewApplication = new Outlook.Application();
Outlook.MailItem myNewMailIoI = myNewApplication.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
//Add Subject
myNewMailIoI.Subject = "IoI - " + myNewDate.Date.ToString("d");
//Set Body Format to RTF
myNewMailIoI.BodyFormat = Outlook.OlBodyFormat.olFormatRichText;
//Converting RAW RTF data from string to bytes. THIS IS THE FIX THAT WAS NEEDED TO MAKE IT WORK
string myNewText = Clipboard.GetText(TextDataFormat.Rtf);
byte[] myNewRtfBytes = Encoding.UTF8.GetBytes(myNewText); //This line cost me way too many hours of lost sleep!!!
//Inserting RTF bytes into RTFBody property
myNewMailIoI.RTFBody = myNewRtfBytes;
myNewMailIoI.Display(); //Displays the newlycreated email
//If this section is uncommented, it will add a properly formatted HTML text to the email
//myNewMailIoI.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
//myNewMailIoI.HTMLBody = "<p>This works for the HTMLbody property!!!</p>" + "<p style='color: green; font-size:10pt; font-family:arial'>this renders properly</p>";

Similar Messages

  • How ias integrate with Snacktory for getting main text from an html page

    Hi All,
    i am new to endeca and ias, i have an requirement, need to get main text from whole html page before ias save text to Endeca_Document_Text property,
    as ias save all text in page to endeca_document_text property, it is not ok for reading when show in web page, i use an third party API to filter out the main text from original page,
    now i want to save these text to endeca_document_text property,
    an another question,
    i get zero page when doing the logic of filtering main text from original html text in ParseFilter( HTMLMetatagFilter implements ParseFilter) using Snacktory.
    if only do little things, it will work fine, if do more thing, clawer fail to crawl page. any one know how to fix it.
    log for clawler.
    Successfully set recordstore configuration.
    INFO    2013-09-03 00:56:42,743    0    com.endeca.eidi.web.Main    [main]    Reading seed URLs from: /home/oracle/oracle/endeca/IAS/3.0.0/sample/myfirstcrawl/conf/endeca.lst
    INFO    2013-09-03 00:56:42,744    1    com.endeca.eidi.web.Main    [main]    Seed URLs: [http://www.liferay.com/community/forums/-/message_boards/category/]
    INFO    2013-09-03 00:56:43,497    754    com.endeca.eidi.web.db.CrawlDbFactory    [main]    Initialized crawldb: com.endeca.eidi.web.db.BufferedDerbyCrawlDb
    INFO    2013-09-03 00:56:43,498    755    com.endeca.eidi.web.Crawler    [main]    Using executor settings: numThreads = 100, maxThreadsPerHost=1
    INFO    2013-09-03 00:56:44,163    1420    com.endeca.eidi.web.Crawler    [main]    Fetching seed URLs.
    INFO    2013-09-03 00:56:46,519    3776    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    come into EndecaHtmlParser getParse
    INFO    2013-09-03 00:56:46,519    3776    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    come into HTMLMetatagFilter
    INFO    2013-09-03 00:56:46,519    3776    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    meta tag viewport ==minimum-scale=1.0, width=device-width
    INFO    2013-09-03 00:56:52,889    10146    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    come into EndecaHtmlParser getParse
    INFO    2013-09-03 00:56:52,889    10146    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    come into HTMLMetatagFilter
    INFO    2013-09-03 00:56:52,890    10147    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-1]    meta tag viewport ==minimum-scale=1.0, width=device-width
    INFO    2013-09-03 00:56:59,184    16441    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    come into EndecaHtmlParser getParse
    INFO    2013-09-03 00:56:59,185    16442    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    come into HTMLMetatagFilter
    INFO    2013-09-03 00:56:59,185    16442    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    meta tag viewport ==minimum-scale=1.0, width=device-width
    INFO    2013-09-03 00:57:07,057    24314    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    come into EndecaHtmlParser getParse
    INFO    2013-09-03 00:57:07,057    24314    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    come into HTMLMetatagFilter
    INFO    2013-09-03 00:57:07,057    24314    com.endeca.eidi.web.parse.HTMLMetatagFilter    [pool-1-thread-2]    meta tag viewport ==minimum-scale=1.0, width=device-width
    INFO    2013-09-03 00:57:07,058    24315    com.endeca.eidi.web.Crawler    [main]    Seeds complete.
    INFO    2013-09-03 00:57:07,090    24347    com.endeca.eidi.web.Crawler    [main]    Starting crawler shut down
    INFO    2013-09-03 00:57:07,095    24352    com.endeca.eidi.web.Crawler    [main]    Waiting for running threads to complete
    INFO    2013-09-03 00:57:07,095    24352    com.endeca.eidi.web.Crawler    [main]    Progress: Level: Cumulative crawl summary (level)
    INFO    2013-09-03 00:57:07,095    24352    com.endeca.eidi.web.Crawler    [main]    host-summary: www.liferay.com to depth 1
    host    depth    completed    total    blocks
    www.liferay.com    0    0    1    1
    www.liferay.com    1    0    0    0
    www.liferay.com    all    0    1    1
    INFO    2013-09-03 00:57:07,096    24353    com.endeca.eidi.web.Crawler    [main]    host-summary: total crawled: 0 completed. 1 total.
    INFO    2013-09-03 00:57:07,096    24353    com.endeca.eidi.web.Crawler    [main]    Shutting down CrawlDb
    INFO    2013-09-03 00:57:07,160    24417    com.endeca.eidi.web.Crawler    [main]    Progress: Host: Cumulative crawl summary (host)
    INFO    2013-09-03 00:57:07,162    24419    com.endeca.eidi.web.Crawler    [main]   Host: www.liferay.com:  0 fetched. 0.0 mB. 0 records. 0 redirected. 4 retried. 0 gone. 0 filtered.
    INFO    2013-09-03 00:57:07,162    24419    com.endeca.eidi.web.Crawler    [main]    Progress: Perf: All (cumulative) 23.6s. 0.0 Pages/s. 0.0 kB/s. 0 fetched. 0.0 mB. 0 records. 0 redirected. 4 retried. 0 gone. 0 filtered.
    INFO    2013-09-03 00:57:07,162    24419    com.endeca.eidi.web.Crawler    [main]    Crawl complete.
    ~/oracle/endeca
    -======================================
    source code for parsefilter
    package com.endeca.eidi.web.parse;
    import java.util.Map;
    import java.util.Properties;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.log4j.Logger;
    import org.apache.nutch.metadata.Metadata;
    import org.apache.nutch.parse.HTMLMetaTags;
    import org.apache.nutch.parse.Parse;
    import org.apache.nutch.parse.ParseData;
    import org.apache.nutch.parse.ParseFilter;
    import org.apache.nutch.protocol.Content;
    import de.jetwick.snacktory.ArticleTextExtractor;
    import de.jetwick.snacktory.JResult;
    public class HTMLMetatagFilter implements ParseFilter {
        public static String METATAG_PROPERTY_NAME_PREFIX = "Endeca.Document.HTML.MetaTag.";
        public static String CONTENT_TYPE = "text/html";
        private static final Logger logger = Logger.getLogger(HTMLMetatagFilter.class);
        public Parse filter(Content content, Parse parse) throws Exception {
            logger.info("come into EndecaHtmlParser getParse");
            logger.info("come into HTMLMetatagFilter");
            //update the content with the main text in html page
            //content.setContent(HtmlExtractor.extractMainContent(content));
            parse.getData().getParseMeta().add("FILTER-HTMLMETATAG", "ACTIVE");
            ParseData parseData = parse.getData();
            if (parseData == null) return parse;
            extractText(content, parse);
            logger.info("update the content with the main text content");
            return parse;
        private void extractText(Content content, Parse parse){
            try {
                ParseData parseData = parse.getData();
                if (parseData == null) return;
                 Metadata md = parseData.getParseMeta();
                ArticleTextExtractor extractor = new ArticleTextExtractor();
                String sourceHtml = new String(content.getContent());
                JResult res = extractor.extractContent(sourceHtml);
                String text = res.getText();
                md.set("Endeca_Document_Text", text);
            } catch (Exception e) {
                // TODO: handle exception
        public static void log(String msg){
            System.out.println(msg);
        public Configuration getConf() {
            return null;
        public void setConf(Configuration conf) {

    but it only extracts URLs from <A> (anchor) tags. I want to be able to extract URLs from <MAP> tags as wellGee, do you think you could modify the code to check for "Map" attributes as well.
    Can someone maybe point a page containing info on the HTML toolkit for me?It's called the API. Since you are using the HTMLEditorKit and an ElementIterator and an AttributeSet, I would start there.
    There is no such API that says "get me all the links", so you have to do a little work on your own.
    Maybe you could use a ParserCallback and every time you get a new tag you check for the "href" attribute.

  • Getting the text from a JTextArea...

    hi, I'm making a perfect calculator program and I'm trying to add a Note Pad function to it, I also want to hide that so the other interface can be used; I can get it hided and come again but I'm wondering how could I get the text from the JTextArea INCLUSIVE the enters that are made withing it, so:
    theString = jTextArea1.getText();only gives me the text and no enters; suggestions?

    I think I displayed it wrongTwo things to keep in mind...
    Certain Swing components will just ignore newlines, so you have to be careful where/how you're displaying your multiline text strings. Some components will display it all as one line, some will only display the top line, some will even show \n instead of doing the newline. It all just depends.
    And JTextArea does support word wrapping, so just because it looks like there's a newline, there may not be one.

  • My daughter recently broke her iphone 4.  We had a spare so we exchanged SIM card.  Now that we are linked in the cloud, I am getting all of her text messages and when I text her i get a text from my  number.  What should i try next?

    My daughter recently broke her iphone 4.  We had a spare so we exchanged SIM card.  Now that we are linked in the cloud, I am getting all of her text messages and when I text her i get a text from my  number.  What should i try next?

    stop using the same Apple ID for iMessage on both phones

  • How do I get old texts from the Cloud

    How do I get old text from the Cloud?   Issues with my phone forced the Verizon Tech to wipe my phone and start over.  He said the Cloud would hold everything and I could retrieve it later.   I can't find any of the saved texts that I had.   Help please.

    Had you previously backed up your texts to the cloud? Yes, you can save things in the cloud, but you must first set it up to do so.

  • I have a friend that has the IPhone and I have Straight Talk, what the issue is,when I send picture texts from my ST phone to his IPhone,he always tells me  he doesn't receive them.Why is this happening?

    I have a friend that has the IPhone and I have Straight Talk, what the issue is,when I send picture texts from my ST phone to his IPhone,he always tells me  he doesn't receive them.Why is this happening?

    You got the new iphone?????   I have same problem.  I transferred audiobooks to device to find no audiobooks on device (despite it being in iTunes as if it was).  Have you found a solution?????   I even tried to change import settings on format transfer but hasn't worked. 

  • I have an 06' macbook and I just bought an 07' macbook.. The 06' has os x 10.6 but the 07' has 10.5.. I no longer have the disk for snow leopard. Is there ANY way to get snow leopard from the old computer to the other without having to buy it again?

    I have an 06' macbook and I just bought an 07' macbook.. The 06' has os x 10.6 but the 07' has 10.5.. I no longer have the disk for snow leopard. Is there ANY way to get snow leopard from the old computer to the other without having to buy it again?

    Technical issues aside, there's still a legal issue.
    Neither 2006 nor 2007 MacBooks shipped with Snow Leopard 'factory' installed. OS X 10.6 Snow Leopard became available in September 2009. So you purchased and installed a Snow Leopard upgrade disc on the 2007 system at some point.
    If your Snow Leopard upgrade was a single-user copy, then legally, you need to purchase another one for the second computer. If your Snow Leopard upgrade was a Family Pack 5-user license, then you're good to go.
    http://store.apple.com/us/question/answers/product/MC574Z/A?pqid=QTUXD7AF4YU9FJD YUTDPCKYKUDDDXKHTK
    If you have an active MobileMe account, Apple was giving away a single-user upgrade copy of Snow Leopard for a limited time, and you should have received an email with a link, or been offered the opportunity when you signed in to your MobileMe account on the web:
    http://www.macrumors.com/2012/04/24/free-snow-leopard-discs-for-mobileme-users-n ow-arriving/
    Worst case, single-user Snow Leopard upgrade discs are $29 retail, direct from Apple. I'd hate to have two computers and no OS installation CD's for whatever version I'm currently using.

  • Regarding passport registration issues, I need to have a letter from you including both the old and new imei numbers. Could you please send me an email mentioning that I have changed the phones with the given imei numbers?

    Regarding passport registration issues, I need to have a letter from you including both the old and new imei numbers. Could you please send me an email mentioning that I have changed the phones with the given imei numbers?

    You're not addressing Apple here. This is a user-to-user technical support forum. If you want to contact Apple, use the Contact Us link at the bottom right of every page for information on how to do so.
    Best of luck.

  • Get the month from a date column with the calculated column

    I am trying to get the month from a date field with the help of calculated column. However I get this syntax error whenever I want to submit the formula:
    Error 
    The formula contains a syntax error or is not supported. 
    the default language of our site is German and [datum, von] is a date field.

    Hi,
    I have created two columns
    Current MM-YY
    Calculated (calculation based on other columns)
    Today
    Date and Time
    Current MM-YY is calculated value with formula as
    =TEXT(Today,"mmmm")
    But the output shows as December instead of May.
    I have tried =TEXT([Datum, von];"mmmm") but no help.
    I am trying to populated the column automatically with current month..ex: if its May the field should show May, next month it should show June an so on.
    Any kind help is grateful.
    Regards,
    Pradeep

  • I am unable to delete whole texts from left-swipe. i click delete and they dissappear. But then i can't send or recieve texts. i reboot phone and deleted message reappear. i've synced, backup, everything. Help!

    I am unable to delete whole texts from left-swipe. i click delete and they dissappear. But then i can't send or recieve texts. i reboot phone and deleted message reappear, but i am able to continue send/recieving texts.. i've synced, backup, everything. Help! I am doing this beacuse in my space on my phone my doucments and data are taking up 9GB of space, and i don't know why other than in my phone it says messages are taking up 8GB or so. I am running ios 7.0. I have synced my phone with itunes, backed up, reboots after deleting the texts, they never vanish, i have even restored from itunes and restored from a backup that didn't include the texts after i deleted them.

    actually better to reset your phone and reinstall the latest firmware again after that restore your back up it should be ok

  • HT1329 My old computer crashed and I had to get a new one.  I was unable to save anything from the old computer.  Is there anyway to get my music from my Ipod to my new computer without having to start over with the old cd's again

    My old computer crashed and I had to get a new one.  I was unable to save anything from the old computer.  Is there anyway to get my music from my Ipod to my new computer without having to start over with the old cd's again

    Hello cheech07,
    The following article contains directions that can help get you back on track with iTunes. I'd recommend picking up at 'Part 5' of the 'External drive' section.
    iTunes: How to move your music to a new computer
    http://support.apple.com/kb/HT4527
    Cheers,
    Allen

  • I bought Adobe Photoshop Elements 13 from wal mart today, and when i go to type in my redemption code to get my serial number it says my redemption code is invalid? and yes i have done it with caps and without caps, ive tried everything and I dont know wh

    I bought Adobe Photoshop Elements 13 from wal mart today, and when i go to type in my redemption code to get my serial number it says my redemption code is invalid? and yes i have done it with caps and without caps, ive tried everything and I dont know what to do anymore. I know its non returnable once opened and the package wasnt tampered with when I bought it. im at a loss on what to do

    Redemption Code http://helpx.adobe.com/x-productkb/global/redemption-code-help.html
    -and https://forums.adobe.com/thread/1572504
    Lost serial # http://helpx.adobe.com/x-productkb/global/find-serial-number.html

  • Ihave downloaded iCloud to my new PC and am using windows 7 and office 2010. I cannot get iCloud to come up on Outlook with the choices for CalendCar and contacrts, my iMail account is there, but not the general coud choices. What am I doing wrong.

    I have downloaded iCloud to my new PC and am using Windows 7 and Offie 2010. I cannot get iCloud to come up on Outlook with the choices for Calendar and Contacts, my iMail accnt is there***.me.com, but not the general Cloud choices for calendar and contacts? What am I doing wrong?

    I have I cloud 2.0.2.187 loaded just downloaded yesterday.

  • CS6 doesn't paste latest text from clipboard but older one

    OSX 10.8.2, InDesign CS6
    I cannot paste text from word mac 2011 in Indesign CS6. When I try to paste the text in InDesign the text from before the current copying appears. (although the right text is in the clipboard). The problem is that InDesign shuts down after trying this 3-4 times.
    Does anyone know this problem and has a solution?

    No, its correct but not the text from the last copying but the one before.
    This is how it goes:
    1. I copy text from word
    2. Pasting in InDesign without any problems
    3. Copying another text from word
    4. Pasting in InDesign show the text from step 2 and not the copied text from step 3
    5. delete the pasted text
    6. Pasting again shows the correct text from step 3
    after repeating this 3-4 time InDesign quits
    I hope my explanation is understanable
    best regards

  • How do I get a playlist from my mac to my iphone 4 without synching, How do I get a playlist from my mac to my iphone 4 without synching

    Basically my post is as the title - is it possible to get a playlist from my mac to my iphone 4 without synching the phone to the computer?

    You sync via iTunes
    http://support.apple.com/kb/HT1678?viewlocale=en_US&locale=en_US

Maybe you are looking for

  • Item category copying incorrectly at Invoice

    Dear Experts, I have custom item category ZTAN for my Z order type. For eg, i have an order for Material 1, 100 PCS. Sales order picks item category correctly. But in delivery i hav batch split. Hence Line item 10 -Material 1- 100 pcs, consists of th

  • Printing in Adobe Reader 10.0.1

    I am having an issue with printing in Adobe Reader 10.0.1. When I go and attempt to print a text only 1 page document it takes about 1 to 2 minutes for it to print. During the 1 to 2 minutes the computer gives the impression that it has crashed (free

  • How to copy an Object with sequencing primary key?

    Hi, I have a use case here to copy all the informations and create a new object? The draft process i am using is: obj original = session.readObject; obj target = uow.readObject; if(target is not there) { target = uow.registerObject(new target()) targ

  • Alerts in delegate iCal 6.0 in Mountain Lion not allowing to set default

    I'm using iCal 6.0 with OSX 10.8.2 When syncing iCal with my Google calendars all is well. However, when I add an event in any one of the delegate calendars in switches the default alert from "None" to "9 a.m. the day before" etc. I have logged into

  • IPOD Freezes Itunes and Memory is full of "Other"

    I have an 80g Ipod classic and i recently updated my itunes to version 10.6.1 (7).  After my latest sync, my ipod now has no music but 1/2 the memory is full with "other".  I have reset my ipod several times but the music fails to appear.  I cannot r