Sending emails with signatures via C# - c#

I have a the following setup to send emails from my c# Application :
SmtpClient (under System.Net.Mail namespace) to do the actual sending once everything is in place and set the 'IsBodyHtml' property of the Message object to True
Using the dll from Sautinsoft I convert a simple rtf file which contains the formatting of the email and convert it to a HTML string which I then use as the body of the mail.
It works great just as it is and I have sent a few test emails to myself and all the appropriate formatting is retained. However i am having a problem with images - The dll converts images to a img tag and uses the base 64 format of the image as the data source, this works fine if you view it as a html page, but sending it as the body of you email produces problems. Email clients such as Yahoo don't mind embedded images but Gmail does not play nice with this methodology. The only image that should appear in the emails I'm sending is the signature image located at the bottom of each email. Using signatures in the native Gmail client in your browser poses no problems since the image has a link to a actual file on a server somewhere, but sending emails with signatures via a C# Application seems to be a different story. Any suggestions?
Thank you for your time.

You may consider automating Outlook from a C# application. See How to automate Outlook and Word by using Visual C# .NET to create a pre-populated e-mail message that can be edited. Also you can find a sample code - C# app automates Outlook (CSAutomateOutlook).

If you are talking about RTF2HTML, you may add any images in a separate folder (no include in body of HTML):
string inpFile = #"..\..\..\..\example.docx";
string outFile = Path.GetFullPath(#"Result2.html");
string imgDir = Path.GetDirectoryName(outFile);
RtfToHtml r = new RtfToHtml();
// Set images directory
HtmlFixedSaveOptions opt = new HtmlFixedSaveOptions()
{
ImagesDirectoryPath = Path.Combine(imgDir, "Result_images"),
ImagesDirectorySrcPath = "Result_images",
// Change to store images as physical files on local drive.
EmbedImages = false
};
try
{
r.Convert(inpFile, outFile, opt);
}
catch (Exception ex)
{
Console.WriteLine($"Conversion failed! {ex.Message}");
}
As the result you will see HTML file with linked images in folder.

Related

Getting the attachment contents of an rtf mail in vsto c#

we are trying to get the content of the attachment's of the in the rtf mail but I have tried to search using different terms but have not found any reliable solution . can someone please help me to get the source of the attachment's as we get them in the html format.
The Outlook object model doesn't provide any property or method for getting the attachment content. To get the file attached you need to save it to the disk and then read the content from the there.
Also you may consider using a low-level API on which Outlook is based on - Extended MAPI. It allows getting the binary data of the attached file. Try using the Attachment.PropertyAccessor.GetProperty method while passing in the value "http://schemas.microsoft.com/mapi/proptag/0x37010102" (PR_ATTACH_DATA_BIN).
set msg = Application.ActiveExplorer.Selection(1)
set attach = msg.Attachments(1)
set ps = attach.PropertyAccessor
v = ps.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37010102")
debug.print ps.BinaryToString(v)
On the low level (Extended MAPI in C++ or Delphi), you need to open the PR_ATTACH_DATA_OBJ property as IStorage and extract the data from there (it depends on the actual type of the attachment). You can see the data in the streams in OutlookSpy (I am its author) - select the message, click IMessage button on the OutlookSpy ribbon, go to the GetAttachmentTable tab, double click on the attachment to open it, select the PR_ATTACH_DATA_OBJ property, right click, select IMAPIProp::OpenProperty, then IStorage. Raw data will be there as well as an image representing the attachment (so that Outlook won't have to start the host app when rendering the message).
If using Redemption is an option (I am also its author, it can be used from any language including C# and VBA), its version of RDOAttachment.SaveAsFile method handles OLE attachments for most popular formats (Word, Excel, bitmap, Power Point, Adobe PDF, etc.) - create an instance of the RDOSession object (using either CrealeOleObject or RedemptionLoader) and use RDOSession.GetRDOObjectFromOutlookObject method (pass either MailItem or Attachment object) to get back RDOMail or RDOAttachment object respectively.
i have been found a solution for getting the images content from the rtf mail directly whiteout hitting the low level api or anything.
the solution is not a straight forward one
save the mail to the disk using oDoc.SaveAs2(filepath, WdSaveFormat.wdFormatFilteredHTML);
after saving the mail you will get the folder which you save a .htm doc
now read the .htm doc
get the all the image nodes of the .htm doc
using the image nods you can get src attribute of the image node
using the src value of the image you get the image directly from the disk itself and you can use that image

Convert EML to MSG c# Using EWS

I need help with converting EML to MSG, using the Exchange web service (EWS) in a Outlook Web Add-In. When i create an EML file from the MimeContent (EmailMessage.MimeContent.Content), the file output looks bad, some tags are not convert currently.
The files open good just from Windows mail app, but from Ooutlook(2016) looks bad.
I tried to find some solution from Microsoft and found this Independentsoft, a third party solution, and it is work great. the file looks good while the format is MSG. but it is to expansive licence solution for the customer (used 30 days demo).
This is what i used and work well, and try to found something like this:
//1.This code use the EWS mimeContent(the message on bytes - eml format)
//2.Create Independentsoft message object
//Independentsoft.Msg.Message constractor do the convert by
// making an msg object from an eml object.
//3. save the msg file.
Independentsoft.Email.Mime.Message mimeMessage = new Independentsoft.Email.Mime.Message(emailMessage.MimeContent.Content);
Independentsoft.Msg.Message msgMessage = Independentsoft.Msg.Message(mimeMessage);
using (MemoryStream memStream = new MemoryStream(emailMessage.MimeContent.Content.Length))
{
Directory.CreateDirectory(TempMsgDirectory);
msgMessage.Save(TempMsgDirectory + "mail.msg", true);
}
I am not aware of any Outlook problems with displaying EML files. It uses the same EML parser used to parse incoming POP3/IMAP4 messages. Please post a specific EML file that Outlook does not display correctly.
As for converting EML files to MSG, you can also use Redemption (I am its author) and its RDOSession.CreateMessageFromMsgFIle and RDOMail.Import methods. Just keep in mind that it requires the MAPI system to be present to function properly, which means Outlook must be installed locally.
Off the top of my head:
RDOSession session = new RDOSession();
RDOMail msg = session.CreateMessageFromMsgFile(TempMsgDirectory + "mail.msg");
msg.Import(TempMsgDirectory + "YouEmlFile.eml", rdoSaveAsType.olRFC822);
msg.Save();
Also keep in mind that retrieving MIME content from Exchange might not be the best idea - you will lose all MAPI specific properties and will end up with a corrupted message if the original was in the RTF format (with or without embedded OLE objects). In that case, you can use ExportItems EWS operation. Its format is not documented, but it is very close to the MSG format, and you can convert it to MSG using code similar to that above, but specifying olFTS format instead of olRFC822.

How to add attachments to .oft file with Aspose

I want to create a .oft file with C# .
The oft file needs to have a html body and attachments.
I found that i should be able to do this using Aspose.
However when i run my code the attachments never get added.
( They are added to the AttachmentCollection but aren't shown when the .oft file is opened in outlook. The oft file does get 20x as large so i presume the raw attachment data is added. )
MailMessage message = new MailMessage();
var attachmentGif = new Attachment(#"C:\inetpub\wwwroot\IntranetKbs\Website\Email logos\" + language + #"\KBSFRB_logo_" + language + #".gif");
var attachmentEps = new Attachment(#"C:\inetpub\wwwroot\IntranetKbs\Website\Email logos\" + language + #"\KBSFRB_logo_" + language + #".eps");
message.Attachments.Add(attachmentGif);
message.Attachments.Add(attachmentEps);
Below you can see some information about the attachments after they are added to the AttachmentList.
If you know what could cause this, or know an other way to create .oft files you help and comments would be greatly appreciated!
If you have to display the images in message's HTML body, you need to include them as linked resource rather than regular attachments. This should serve your requirements of adding image to the message body and display it in MS Outlook.
Note: I work with Aspose as Developer Evangelist.

C# Pdf Attachment damaged when sent to yahoo mail addresses

I'm trying to send an Email with an attached PDF file. When I send it to any other mail provider it works just fine, but when I send it to a yahoo email address, the receiver gets a damaged pdf file. The exact message it gives is:
Adobe Reader could not open 'Filename.pdf' because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded).
Because the other email providers were working, I used the following code specifically for yahoo addresses.
if (thisItem.EmailAddress.ToUpper().Contains("YAHOO")){
ContentType contentType = new ContentType();
contentType.CharSet = Encoding.UTF8.WebName;
Attachment theFile = new Attachment(attachmentPath, contentType);
theFile.Name = theFile.Name.Replace("_","");
mm.Attachments.Add(theFile);
}
I've tried a variety of CharSets on the ContentType, hoping that would fix something, no change. I also tried different TransferEncodings on theFile, also no fix. I read somewhere that the file name could cause problems if it had special characters so I removed all the underscores in the name, all that's left is some letters and numbers. I'm not sure what else to try at this point. Any suggestions?

Using an HTTP handler in ASP.NET to generate an image for display in email

I'm generating a barcode image as the response from an HTTP handler, like so:
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
context.Response.ContentType = "image/Jpeg";
MemoryStream ms = new MemoryStream();
Bitmap objBitmap = GenerateBarcode(context.Request.Params["Code"]);
objBitmap.Save(ms, ImageFormat.Jpeg);
context.Response.BinaryWrite(ms.GetBuffer());
}
I go to http://www.MyWebsite.com/MyProject/BarCode.aspx?code=12345678 and it works great. Likewise I stick <img alt="" src="http://www.MyWebsite.com/MyProject/BarCode.aspx?code=12345678"> on my webpage and it works great. But I stick that same image tag in an HTML email and it doesn't show up (at least not in MS Outlook 2007; I haven't tested other email clients yet.)
I'm guessing this is somehow related to the fact that I'm using an HTTP handler, as other, static images in the email are showing up fine. How can I fix this so that the image shows up? (I can't just use a static image because the code is determined at the time the email is sent.)
Update:
It turns out I hadn't noticed a key detail. The image isn't just not showing up; rather the image src attribute is getting replaced with "http://portal.mxlogic.com/images/transparent.gif". I've determined that using the .aspx or .ashx extensions triggers this replacement (or probably any extension except those expected for images like .gif or .jpg), and that including a query string in the URL also triggers this, even when it's a standard image extension. I guess it's some overzealous security feature. So including an image like BarCode.aspx?code=12345678 just isn't going to work.
It occurs to me that I could do something like <img alt="" src="http://www.MyWebsite.com/MyProject/12345678/BarCode.jpg"> and then create a handler for all files named BarCode.jpg. Here 12345678/ isn't an actual path but it wouldn't matter since I'm redirecting the request to a handler, and I could scrape the code value from that phony path in the URL. But, I'd probably have to change some IIS setting to have requests for .jpg files handled by ASP.NET, and I'd want to still make sure that other JPEGs besides my BarCode.jpg loaded normally.
Honestly, I'm not sure if it's worth the hassle.
Microsoft Office Outlook 2007 uses the HTML parsing and rendering engine from Microsoft Office Word 2007 to display HTML message bodies. more
which leaves us with some hairy points
The limitations imposed by Word 2007 are described in detail linked off in the article, but here are a few highlights:
no support for background images
(HTML or CSS)
no support for forms
no support for Flash, or other
plugins
no support for CSS floats
no support for replacing bullets with
images in unordered lists
no support for CSS positioning
no support for
animated GIFs
i think your best bet would be to embed the image using the LinkedResource class, something like
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("...");
mail.To.Add("...");
//set the content
mail.Subject = "Test mail";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image." ", null, "text/html");
//create the LinkedResource (embedded image)
LinkedResource logo = new LinkedResource(GenerateBarcode(Code)));
logo.ContentId = "logo";
htmlView.LinkedResources.Add(logo);
mail.AlternateViews.Add(htmlView);
//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);
I don't know why it doesn't work but if you are saying that static images from the site hosting the handler work fine here's a slightly modified version you might try:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
using (var image = GenerateBarcode(context.Request.Params["Code"]))
{
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
No need to clear the response in a generic handler as there's nothing written yet
Content-Type is image/jpeg
No need of intermediary memory stream, you could write directly to the response
Make sure to properly dispose the bitmap
You will have to put the image as an attachment, or use html in the mail. Probably your error happends due to Outlook though.
This link suggests the problem, as you suggested is a security/anti-SPAM feature causing the problem (mxlogic.com points to a McAfee product)

Categories

Resources