C# html Email - Div/Text over Image - c#

I'm trying to create a nice looking email for when a user registers on my website however I am not able to display the text over an image the usual way. Instead, the texts are displayed below the image.
I know I can't use StyleSheets, and that I should stick to CSS 1.4..
I'm having a background image which i'm stretching (by setting its width and height) and I would like to put some text on top of this image. In normal html, I can use css methods such as float: left; position: absolute for the div to be floating over the image. But this doesn't work within the C# code because it gets truncated in most email clients.
The image will only display if it is written in the following way:
<div style='width: 580px; font-family: Calibri; font-size:13px;'>
<img style='height: 45px; width: inherit;' src='http://www.somedomain.com/mail/background.png' />
Test
Test2
Test3
</div>
I tried to embed the code above within a style and it simply doesn't work. For example:
<div style='background:url(images/background.png); position: absolute; top:45px; width:550px; padding: 15px;'> SOME TEXT HERE </div>
OR
<div style='background-image:url(images/background.png); position: absolute; top:45px; width:550px; padding: 15px;'> SOME TEXT HERE </div>
OR
<table>
<tr>
<td style="background-image: url(background.png);">Testing Page</td>
</tr>
</table>
If you change "background-image: url(background.png);" to "background:red;" it works and this is confusing!
How do I make this work properly in most email clients as well? (Gmail, Hotmail, Outlook, Thunderbird, Windows Mail, etc.)
Thanks for any help you can provide :)

You should probably check out all of your emails in Outlook 2007. Microsoft really broke the capabilities for HTML in Emails by using the rendering engine of MS Word. To that end background-image is not recognized by Outlook 2007. Here is the MSDN on supported HTML in Outlook. Use outlook as your base line as it's support is the most basic.

Iv had similar issues with images in html and images inside an email. I solved the Image issue by using an inline attachment. The trick is to use a content id to set the image.
Hopefully this code will help:
EDIT: Width and Height settings on the actual image don't seem to work though . . . :/
string contentID = "Image1.gif".Replace(".", "") + "#test";
// create the INLINE attachment
string attachmentPath = Server.MapPath("Images/Image1.gif");
inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/gif";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
//then add in the message body
//stringbuilder to construct the message
sb = new StringBuilder();
sb.Append("<div style=\"font-family:Arial\"> Hello World!<br /><br /><img src=\"##IMAGE##\" alt=\"\" Width=\"250px\" Height=\"250px\"><br /><br /></div>");
//creating the message with from and to and the smpt server connections
mail = new MailMessage("SendersEmail#Address.com", "RecieversEmail#Address.com");
SmtpServer = new SmtpClient("smtp.gmail.com"); //Add SMTP settings into the Web.Config --> ConfigurationManager.AppSettings["MyCustomId"]
mail.Subject = "Testing Emails";
mail.IsBodyHtml = true;
mail.Body = sb.ToString();
mail.Attachments.Add(inline);
// replace the tag with the correct content ID
mail.Body = mail.Body.Replace("##IMAGE##", "cid:" + contentID);

You can't use relative urls (for example "url(background.png)" or "url(images/background.png)" because it's relative to what? the email message? The email message has no folders, file system, etc. as does a web server.
You have two choices: use the complete url syntax as you did in the first example or create a MimeHtml message (MHTML). In MHTML, you can bundle an image in with your email and may be able to reference it in the way you're hoping.

I hate being the bearer of bad news, but you can't cross-platformly (is that a word?) have a background image and/or stacked elements in HTML emails.

You're trying to use CSS features that are not supported by all major email viewers. Try taking a look here to see what's supported and what's not:
http://www.campaignmonitor.com/css/
There's also a sitepoint book which you might be interested in:
http://www.sitepoint.com/books/htmlemail1/

Related

How to display image stored on the network in asp.net (c#)

How to display image stored on the network in asp.net (using c#). I want img src to be the one given below:
\\pgapp\folder\image.jpg, where pgapp is the shared drive on the network.
I am using these codes but its not displaying the image on the webpage.
originalImage2.ImageUrl=#"\\pgapp\folder\image.jpg";
or
originalImage2.Attributes["src"]=ResolveUrl(#"\\pgapp\folder\image.jpg");
<div ID="imgContainer" runat="server" style="width: 400px; height: 400px; overflow:auto; border: solid 1px black;
padding: 10px; margin-bottom: 5px;" >
<asp:Image ID="originalImage2" runat="server" />
</div>
You will hit 2 problems:
Browsers normally can't access server shares (unless it is on the same network). You need to expose image through your site somehow so it visible like http://myserver/image/image1.jpg
"NTLM one hop" - your server will not be able to read files from remote server if you start rendering image through your server. You just need to verify if you have the problem and read about it.
To display images stored on a network in a users web browser do something like the following:
Convert the image to it's base64 counterpart and display:
// PhotoId is the network file path and name.
string photoId = "\\Photos\2015-May\390828d1-8f20-4fe9-9287-13d03894e9c0.jpg"
// Call to display the networked images.
lbl_images.Text += "<img src='" + this.PhotoBase64ImgSrc(photoId) + "' height='60px' width='60px' alt='photo' />";
// Supporting function that converts an image to base64.
protected string PhotoBase64ImgSrc(string fileNameandPath)
{
byte[] byteArray = File.ReadAllBytes(fileNameandPath);
string base64 = Convert.ToBase64String(byteArray);
return string.Format("data:image/gif;base64,{0}", base64);
}
If you want to display images which are store in the network path then change below setting in IIS,
Navigate to IIS.
Navigate to website in Sites folder.
Select application website and navigate to right side Actions menu and click on View Virtual Directories.
Click on Add Virtual Directories and specify an alias as "images" and physical path as "network drive path".
Test settings and Save it.
Refresh application pool and test whether image is rendering or not.

EWS Managed API - Save Draft with inline Images

I am trying to create emails for my users using EWS Managed API 1.1, and need to use email templates our designers have created. I was able to successfully attach image (say header.png) and add an image tag like this (using cid: before the image name) in the html body.
<img width=683 height=27 src="cid:header.png" alt="Header">
This works when I use msg.SendAndSaveCopy() method. It renders perfectly fine in both Sent Mail folder and the recipients inbox. However it is not working when I try to use msg.Save() method just to save it as Draft in Drafts folder. It shows images as plain attachments and the body doesn't show images inline. They don't render properly even if I hit send in outlook. I am wondering if I need to do anything special to have these images rendered correctly in outlook Drafts folder.
Any pointers/ help will be greatly appreciated.
Microsoft provided a workaround today to address this issue. Posting the solution for the benefit of the community
string html = #"<html>
<head>
</head>
<body>
<img width=200 height=100 id=""1"" src=""cid:Desert.jpg"">
</body>
</html>";
newMessage.Body = new MessageBody(BodyType.HTML, html);
string file = #"D:\Tools\Desert.jpg";
newMessage.Attachments.AddFileAttachment("Desert.jpg", file);
newMessage.Attachments[0].IsInline = true;
//this is required to fix the issue - Add content id programatically
newMessage.Attachments[0].ContentId = "<Desert.jpg>";
newMessage.Save();

Referencing Stylesheet when sending email in C#

I am dealing with a situation where I should change the font of a HTML body in C sharp using a stylesheet.
I have added a stylesheet to my project with name Stylesheet1.css which contains the code to change the font of a HTML body.
body {
font-size: 10px;
}
I need to reference this stylesheet in source code, where I am processing the HTML body.
I am processing the HTML body as follows.
if(some condition)
{
mail.HTMLBody= ? ? ? ? ;
}
I need to reference the stylesheet in this part. How can I do this?
I would not use external stylesheets for emails. As alot of email clients do not support it.
See http://groundwire.org/support/articles/css-and-email-newsletters
and
http://www.alistapart.com/articles/cssemail/
As some clients like hotmail remove the 'body' tag all togeather so your example in your question will not work. So you can instead wrap your email in a DIV and use inline styles so you get best support for all email clients.
A list of what is supported by which client is here http://css-discuss.incutio.com/wiki/Style_In_Email
Edit
You should be able to set the font-size like this
<div style="font-size:10px;">
your email content here
<p style="font-size:14px;">
some bigger text
</p>
</div>
I agree with Daveo's answer - you are best off embedding styles directly rather than linking out to an external CSS
There is a very, very extensive matrix of styles & features that are and aren't supported by the popular email apps (outlook/gmail/yahoo mail/etc) at http://www.campaignmonitor.com/css/
http://htmlemailboilerplate.com/ is a really good starting point for getting html and css right in emails.

Change font of HTMLbody in C#

I am using mailitem.HTMLBody to process the text of an email body.
The entire body of the email can be accessed through mailitem.HTMLBody.
How can I change the font of the entire email body in C#? e.g Set font size as 10.5 and font as Consolas
Outlook.MailItem mailItem = (Outlook.MailItem)selection[1];
mailItem.HTMLBody = "<font size= 10>";
This does not work.
No.
Don't use <font> tags. This tag has been obsolete for a very long time now.
Instead, use a CSS stylesheet. This would be a separate file which you'd include (it can also be embedded in your main page using the <style> tag in your header, but it's better practice to have it as a separate file)
To set the font globally io your page using CSS, you can do this:
body {
font-size: 10px;
}
Hope that helps.

How to edit a pdf in the browser and save it to the server

Here are the requirements, the users needs to be able to view uploaded PDFs in the browser. They need to be able to add notes to the PDF and save the updated PDF to the server without having to save it to their machine and open it outside the browser.
Any ideas on how to achieve this are welcomed.
by the way I am working with an asp.net website (in C#).
I have no control over what the pdf looks like. It is uploaded client-side then other users need to view and an notes on top of the pdf.
The solution that I was thinking is to render the PDF to a jpeg and use javascript to plot coordinates of where the note should go.
here is a quick example of the html and javascript that create the json of note (using jQuery.)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<style type="text/css">
*
{
margin:0;
padding:0;
}
#PDF
{
position:absolute;
top:0;
bottom:0;
width:600px;
height:800px;
background:url(assets/images/gray.png) repeat;
float:left;
}
#results
{
float:right;
}
.comment
{
position:absolute;
border:none;
background-color:Transparent;
height:300px;
width:100px;
overflow:auto;
float:left;
top:0;
right:0;
font-family: Arial;
font-size:12px;
}
div.comment
{
padding-top:-20px;
}
.comment a.button
{
display:block;
padding-top:-20px;
}
</style>
</head>
<body>
<div>
<div id="PDF"></div>
<div id="results">
</div>
</div>
</body>
</html>
<script type="text/javascript" src="script/jquery.js"></script>
<script type="text/javascript">
var points = [];
$("#PDF").click(function(e) {
if ($("textarea.comment").length == 0) {
var that = this;
var txt = $("<textarea class='comment'></textarea>").css({ top: e.pageY, left: e.pageX }).blur(function() { $(this).remove(); }).keypress(function(e2) {
if (e2.keyCode == 13 && !e.shiftKey) {
var that2 = this;
$("#PDF").append($("<div class='comment'>").html(that2.value.replace(/\r/gi, "<br>")).css({ top: e.pageY, left: e.pageX }));
$(this).remove();
points.push({ "x": e.pageX, "y": e.pageY, "text": that2.value })
$("#results").append('{ "x": ' + e.pageX + ', "y": ' + e.pageY + ', "text": "' + that2.value + '" }<br/>');
}
});
$(this).append(txt);
txt.each(function() { this.focus(); })
}
});
</script>
So now I need to figure out how to:
Render a pdf to jpeg.
Recreate the PDF putting the annotations on top on it.
You can use GhostScript to render a PDF to JPEG.
Command line example:
gswin32c.exe -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -r300 -sOutputFile=output.jpg input.pdf
You need to call GhostScript via the command line version (as above) or use a wrapper.
A Google search turned up this blog post:
A Simple C# Wrapper for Ghostscript
For creating a new PDF you have two main alternatives:
Modify the JPEG and convert the JPEG into PDF (you can use GhsotScript for the conversion)
Use A PDF library that imports your original PDF and add data on top of that
For PDF libraries see this SO question:
Building PDF Files with C#
My company, Atalasoft, provides components that let you view document images, including PDFs and annotate them and save the annotations back into the PDF. In our product suite, you would need dotImage document imaging and the PDF Reader add-on. You would be using dotAnnotate through our AJAX web controls. Here is a link to our online demo - the document displayed is a TIFF, but you could use a PDF too.
I don't think you will be able to have a user load a pdf in their browser, edit it, then save it to the server without them saving it to their machine and then uploading it to the server.
What you can do is setup a webform with a database backend that can represent the pdf, and when they edit it you can regenerate the PDF using itextsharp and loading the information from the database, that way when the user goes back to edit the PDF you can prepopulate the form with what already exists.
itextsharp is extremely easy to use, here is an example:
string sourceFile = "path/to/pdfTemplate.pdf";
PdfReader reader = new PdfReader(sourceFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream("path/to/store/pdf/filename.pdf", FileMode.Create));
AcroFields fields = stamper.AcroFields;
//now assign fields in the form to values from your form
fields.SetField("input1", input1.Text);
fields.SetField("input2", input2.Text);
//close the pdf after filling out fields
stamper.SetFullCompression();
stamper.FormFlattening = true;
stamper.Close();
then if you wanted to show the actual PDF you could easily
Response.Redirect("path/to/store/pdf/filename.pdf");
We do this using lowagie on a Spring/Java platform.
Users are presented with pre-generated sales tax returns and can add certain manual adjustments in a few fields. We then recompute totals fields based on their manual input and save the whole thing back to our DB.
You can use either PDFSharp or itextsharp to create annotations. Haven't tried PDFSharp annotation but iTextSharp does work. You'll have to handle the editing on the server side. probably copy the file to a temp folder edit it and save it back.
You'll find itextsharp at http://itextsharp.sourceforge.net, annotation example: bottom at the page http://itextsharp.sourceforge.net/tutorial/ch03.html
pdfsharp: http://www.pdfsharp.net
If you are able to buy a third party library I'd pretty much recommend TxTextControl. http://www.textcontrol.com/en_US/
With this control you can write an editor, that lets you use your pdf as a template and allows the user make changes and save them. All within the browser, without the need to manually select a tempfile on the computer. Acessing is pretty much like using the TextProperty of a normal TextBox.
You did not specify what technology limitations you have. If you can consider a Silverlight solution, and you have client computers that support Silverlight, you can easily do this.
Take a look at how Microsoft Sketchflow works, it permits the user to annotate documents in the web browser and the annotations are persisted back to the server.
Here is a company with a commercial control to annotate PDF (and other formats).
Microsoft does this in their Sketchflow player. Here is a video. Of course you would not be using sketchflow but rather implimenting something similar that meets your needs.
As an added bonus Silverlight 4 supports the clipboard as well as drag and drop so that end users could paste something onto the PDF immage as well as drag any file onto it ehich you would then be able to upload to your server.

Categories

Resources