Creating an rtf custom mail item - c#

I'm using redemption to create a custom mail item and save it in the draft folder of my outlook. Currently the mailItem is saved in HTML format. I want to be able to save it in rtf Format. How can I do that ?
Here is the code I am using :
Redemption.RDOSession session = new Redemption.RDOSession();
session.MAPIOBJECT = olApp.Session.MAPIOBJECT;
Redemption.RDOFolder rFolder = session.GetDefaultFolder(Redemption.rdoDefaultFolders.olFolderDrafts);
Redemption.RDOMail rMsg = rFolder.Items.Add("ipm.note.mep");
// modify some custom fields ...
rMsg.BodyFormat = 3;
rMsg.Save();
Outlook.MailItem oMep = olApp.Session.GetItemFromID(rMsg.EntryID);
oMep.BodyFormat = Outlook.OlBodyFormat.olFormatRichText;
oMep.Display(false);
Changing the bodyFormat doesn't seem to work. I also tried the saveAs method with no success. I can change the format manually when the mailItem is open, but I want to do that automatically within my C# code.

Have you tried to set the RDOMail.RtfBody property?

Related

How to Open Outlook file attachment directly not saving it? ( with C# VSTO)

I need to open mail file attachment directly from mail. Let say I have .txt file. I have already attached it to my mail. But now I need to open it, change some words and save it (it is manual part). How can I do this? My code is:
private void button2_Click(object sender, EventArgs e)
{
Outlook.Inspector currInspector = null;
Outlook.MailItem mail = null;
Outlook.Attachments attachments = null;
currInspector = Globals.ThisAddIn.Application.ActiveInspector();
if (currInspector != null) {
mail = (Outlook.MailItem)currInspector.CurrentItem;
attachments = mail.Attachments;
attachments.Add(#"C:\install\CSharp\tulemus.txt", Outlook.OlAttachmentType.olByValue);
}
The Outlook object model doesn't provide any property or method for that. You can try to read the attached files from the cache folder maintained by Outlook. See Finding Outlook temporary folder for email attachments for more information.
Also, you can use a low-level API (Extended MAPI) where you can access the PR_ATTACH_DATA_BIN property, read more about the algorithm in the Opening an attachment article.
In addition to what Eugene suggested - use Attachment.PropertyAccessor or MAPI (C++ or Delphi) to access the PR_ATTACH_DATA_BIN property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x37010102") - you can also use Redemption (I am its author): its RDOAttach.AsText / AsArray / AsStream properties allow to modify attachment contents on the fly

Converting .MSG files to .TXT; Should I use Microsoft.Interop Outlook?

I'm trying to do a conversion from .msg files into .txt. I have two questions.
1)I've been investigating and found the Microsoft.Interop Outlook package and there is a way where I can extract the bodyHTML, To, Sent Date, and a few other properties but I feel as if this is a very manual process because I have to trim out all the html tags such as < br>, &nbsp, a href etc...
Here is my current code...
MailItem mailItem = outlookApp.Session.OpenSharedItem(item) as MailItem;
TextFile textFile = new TextFile(); //collection of properties I am interested in
textFile.To = mailItem.To;
textFile.Subject = mailItem.Subject;
textFile.Sent = mailItem.SentOn.ToString();
textFile.Name = Path.GetFileNameWithoutExtension(item);
var atttach = mailItem.Attachments; //Really just want the names
textFile.Body = RemoveStuff(mailItem.HTMLBody); //manually removing all html tags
textFiles.Add(textFile);
Marshal.ReleaseComObject(mailItem);
Does anyone know if there is a more effective way to do this in C# or a way using Interop that I am not aware of?
2)If I go the interop route, is there a way I can bypass the popup in Outlook asking if I can allow access to Outlook? Seems inefficient if my goal is to create a converter.
Any help is greatly appreciated.
Thanks!
Firstly, why are you using HTMLBody property instead of the plain text Body?
Secondly, you can use MailItem.SaveAs(..., olTxt) to save the message as a text file. Or do you mean something else by txt file?
The security prompt is raised by Outlook if your antivirus app is not up to date. If you cannot control the environment where your code runs, Extended MAPI (C++ or Delphi only) or a wrapper like Redemption (any language - I am its author) are pretty much your only option. See http://www.outlookcode.com/article.aspx?id=52 for more details.
In Redemption, you can have something like the following:
using Redemption;
...
RDOSession session = new RDOSession();
RDOMail msg = session.GetMessageFromMsgFile(TheFileName);
msg.SaveAs(TxtFileName, rdoSaveAsType.olTXT);

Creating and adding Outlook Signature

I've created a html template with a couple of replacement variables.
Adding the created signature-template as signature for reply and new messages does not seem to get outlook to default to it.
//string signatureName = "Example.htm";
//Set via office-interop new signature as default
//using Microsoft.Office.Interop.Word;
Application app = new Application();
var opt = app.EmailOptions.EmailSignature;
opt.NewMessageSignature = signatureName;
opt.ReplyMessageSignature = signatureName;
app.Quit(); //Also tried WdSaveOptions.wdSaveChanges
Marshal.ReleaseComObject(app);
Outlook displays the added signature (TEST_...) but does not recognize it as default signature. Instead it just removed the previous default signature and now has none.
Is there something else required to tell outlook to set it as default ?
The Outlook object model doesn't provide anything for that. Of course, as a workaround you may use the Word object model for setting signatures as you did in the code above:
Application app = new Application();
var opt = app.EmailOptions.EmailSignature;
opt.NewMessageSignature = "Eugene Astafiev";
opt.ReplyMessageSignature = "E.Astafiev";
app.Quit(); //Also tried WdSaveOptions.wdSaveChanges
Marshal.ReleaseComObject(app);
But you need to assign a real HTML markup or text which represents the signature, not an HTML document filename.
Anyway, all settings are stored in the windows registry. See Set Default Signature outlook for more information.
Apparently the problem was something... quite simple.
string signatureName = "Example.htm";
Outlook/Word expects the signature-name without the file-extension. Passing "Example" instead of "Example.htm" worked.

Copying mail body to new mail in outlook by coding in c#

In Outlook 2013, I want the content of the mail body in a new mail programmatically.
Below is my code:
void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
{
Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
Outlook.Application oApp = new Outlook.Application();
Outlook.Explorer oExplorer = oApp.ActiveExplorer();
Outlook.Selection oSelection = oExplorer.Selection;
foreach (object item in oSelection)
{
Outlook.MailItem mi = (Outlook.MailItem)item;
mailItem.HTMLBody = mi.HTMLBody;
}
}
Everything works fine, but the image present in the original mail is not displayed. Instead it shows something like cid:image002.png.
Not sure what is the reason.
Also I want to give it to the client, so I can't save mail content locally.
If you see cid:image002.png statements in the HTML markup of the message body you need to attach embedded items to new emails as well.
The basic principle of adding an embedded image is to attach the image to the item and then using the HTMLBody to write HTML to add the attachment cid as a reference in the HTML.
Attachment attachment = newMail.Attachments.Add(
#"E:\Pictures\image001.jpg"
, OlAttachmentType.olEmbeddeditem
, null
, "Some image display name"
);
string imageCid = "image001.jpg#123";
attachment.PropertyAccessor.SetProperty(
"http://schemas.microsoft.com/mapi/proptag/0x3712001E"
, imageCid
);
newMail.HTMLBody = String.Format(
"<body><img src=\"cid:{0}\"></body>"
, imageCid
);
Be aware, you will need to save the file on disk and the re-attach it to the new email. The Add method of the Attachment class accepts a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.
Also I'd recommend avoiding the foreach loop in the code with OOM objects. Use the for loop instead. It allows to release underlying COM objects instantly. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. You can read more about that in the Systematically Releasing Objects article.
As i understand you want to copy the attachments from existing mailitem to new one... Then you can try this
foreach( var x in mailItem.Attachments)
{
mi.Attachments.Add(x);
}

Generate HTML file at runtime and send as email attachment

I have a project requirement that we need to attach an HTML formatted log sheet to an email that gets sent to a user. I don't want the log sheet to be part of the body. I'd rather not use HTMLTextWriter or StringBuilder because the log sheet is quite complex.
Is there another method that I'm not mentioning or a tool that would make this easier?
Note: I've worked with the MailDefinition class and created a template but I haven't found a way to make this an attachment if that's even possible.
Since you're using WebForms, I would recommend rendering your log sheet in a Control as a string, and then attaching that to a MailMessage.
The rendering part would look a bit like this:
public static string GetRenderedHtml(this Control control)
{
StringBuilder sbHtml = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(sbHtml))
using (HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter))
{
control.RenderControl(textWriter);
}
return sbHtml.ToString();
}
If you have editable controls (TextBox, DropDownList, etc), you'll need to replace them with Labels or Literals before calling GetRenderedHtml(). See this blog post for a complete example.
Here's the MSDN example for attachments:
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
You can use Razor for email templates. RazorEngine or MvcMailer might do the job for you
Use Razor views as email templates inside a Web Forms app
Razor views as email templates
http://www.codeproject.com/Articles/145629/Announcing-MvcMailer-Send-Emails-Using-ASP-NET-MVC
http://kazimanzurrashid.com/posts/use-razor-for-email-template-outside-asp-dot-net-mvc

Categories

Resources