I have this little piece of code
var builder = new BodyBuilder();
var image = builder.LinkedResources.Add(logoPath);
image.ContentId = MimeUtils.GenerateMessageId();
textMsg = textMsg.Replace("{logo}", image.ContentId);
builder.HtmlBody = textMsg;
msg.Body = builder.ToMessageBody();
It works perfectly except that if I use a .png image it isn't attach to the mail but if it is an .svg it is attach. I tried to convert the svg to base64 but it didn't work.
As I show in the images below, if it is a .svg the image is attach at the top of the mail but if it is a.png it doesn't. Is it possible to do the same with .svg? I don't want the attached file.
The issue you are facing is a limitation of the receiving mail client, not anything you are doing wrong with the images in your email message.
The client you are using to receive the message does not support SVG and so has decided that whenever it encounters an SVG image, it will offer it to the user as an attachment.
Related
I am writing an Outlook add-in to be able to insert automatically an image into an email using CID.
However, everytime I add an image as attachment (jpeg), the image is compressed automatically by Outlook and I have a big lost of quality.
Is it possible to avoid compression of images for attachment?
Here is the code that I am using so far:
var attachment = mailItem.Attachments.Add( #"D:\\image.jpg" , Outlook.OlAttachmentType.olEmbeddeditem , null , "Some image display name" );
string imageCid = "image.jpg#123";
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/jpeg"); // PR_ATTACH_MIME_TAG
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", imageCid); // PR_ATTACH_CONTENT_ID
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", true); // Hide attachment in the email
mailItem.HTMLBody = String.Format( "<body><img src=\"cid:{0}\" width='450' height='150' alt=''></body>" , imageCid);
Thanks a lot for any help
Not much you can do if the message is then displayed by Outlook. You can try to add the image immediately prior to it being sent (Aplication.ItemSend event).
Found a problem with saving e-mail to database(as byte[] - already tried with various methods:
saving "RawMessage",
executing Message.
Load via "MemoryStream" etc..),
retrieving it and re sending.
When I send this saved e-mail, recipient does not see inline attached image (in place where image should be is information that picture was not found or couldn't be loaded).
My actual code version:
byte[] toDB = message.RawMessage; // then it goes to DB
//later in code
OpenPop.Mime.Message raw = new OpenPop.Mime.Message(fromDB, true);
//then I fill in new Message object with new values, only body remains the same:
mailMessage.Body = System.Text.Encoding.Default.GetString(raw.FindFirstHtmlVersion().Body);
Thanks :)
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.
I made a mail sender in C# but I'm having trouble with the body of the mail. It only sends the texts without pictures, links and other elements. Not to mention, I used RichTextBox for that purpose.
So now my question is: what component to use to send mail with pictures, links and else?
I also enabled IsBodyHtml to true.
What I want to do is to copy the pictures, links and texts (with different colors and size) from Microsoft Word and paste it to control, and when user gets mail he gets the exact same body and layout as I send them.
You'll need to send it as html.
Save your word doc as html and use that.
For the images in your document you can either point to them via their absolute urls (publicly available via the internet).
Or you could use the LinkedResource class.
With the LinkedResource class your images have to specify a cid in the source.
var inlineLogo = new LinkedResource("path/myfile.png");
inlineLogo.ContentId = Guid.NewGuid().ToString();
var imageHtmlFragment = string.Format("<img alt='My Logo' src='cid:{0}' style='width: 250px;height: 60px;'/>",inlineLogo.ContentId);
var newMail = new MailMessage();
var view = AlternateView.CreateAlternateViewFromString(imageHtmlFragment, null, "text/html");
view.LinkedResources.Add(inlineLogo);
newMail.AlternateViews.Add(view);
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)