How to send an email html template using C#? - c#

I have a Windows Service that sends email alerts to the users, i made a folder and contains all the files and styles like a normal html.
In the properties of Email.html, i selected always copy.
To read that file in my method, i used this:
var path = AppDomain.CurrentDomain.BaseDirectory + "EmailTemplate\\Email.html";
string body = File.ReadAllText(path);
And to replace the text dinamically, just used body.Replace("#Text#", newString)
To send the email i used: MailMessage
And the final result is:
Nothing of the css imported is used, how to load all files?
Note: I edited the image with black lines

Most email clients don't support external stylesheets. You'll need to inline the CSS to get it to show up.
If you don't want to hand-convert things, MailChimp has an inline CSS converter that I've used in the past. There are other utilities/tools out there too.

Related

Link to an external file in iTextSharp

I want to provide links to files uploaded on the server in iTextSharp documents.
The problem I'm facing is the string containing my file path is getting mangled en-route from my code onto the page.
Let's say the full path for the file, I'm trying to link is "C:\site uploads\some_file.txt".
I'm trying to create the link using the "Anchor" object, like so:
string path = "C:\site uploads\some_file.txt";
string name = "some_file.txt";
Anchor anchor = new Anchor(name, new Font(Font.FontFamily.UNDEFINED, 12));
anchor.Reference = path;
pdfDoc.Add(anchor);
ASP.NET C# will double up those backslashes in "path", as it does, but iTextSharp will further alter the string to something like C%5%20site%HCuploads%20some%34file.txt, which does not work as a clickable link in my document. FYI, I know I didn't get my % codes just right; those are offered for example only.
I'm not trying to launch any external applications from my document, I just want to enable the user to download this file. Any advice would be appreciated.
Why do you link to a local file? If someone else downloads that PDF on their machine, it won't have that directory.
The backslashes and colon are escaped.
Use https:// links. If you do want to link to local files, use a file:// link.

Read an HTML/Text file and Send it as a HTML Formated Email in WPF/C#

I have a WPF application that sends out a HTML-formatted email when a button is clicked. The entire email message is in HTML-format and it does work.
However, I was wondering if there was a way to read a html file and send it out rather than writing the whole message in the code behind...keeping all the HTML formatting in-tact.
I tried something like this:
string MessageTosend = File.ReadAllText("path to txt/html file");
But that just sent out an email that only has text (no styling, no html...just the plain text found in the file).
Then I thought, I may have to convert everything:
string MessageTosend = Convert.ToString(File.ReadAllText("path to txt/html file"));
But that does the same thing as before.
Is there a way to do achieve this? Or will I have to stick to having
string MessageTosend = #"<html> ... lots of html stuff ... </html>";
for every button that sends an email?
For notice: The contents of the .txt and .html file I attempted to read from was tested using the same contents of the above string (which, again, works as expected), and without the double quotes (example: width=""100"" and width="100")
Try adding an encoding to your file read:
string MessageTosend = File.ReadAllText("path to txt/html file", Encoding.UTF8);
Try reading a file simply containing < and compare it to the string "<". Repeat for any special characters until you find a mismatch. Then find the character number like this:
(int)MessageTosend[0] // < should be 60 (3C in UTF-8)
Find out what the offending characters are, and we may be able to help. If I read a file, I do not see this problem.

How to get message body without downloading attachment

I am using IMAP4 client called: MailKit.
It works great, but I have a problem on getting body of message without downloading the attachments. I want to show the mail's body text and also what attachments there are,
but only if a user clicks on the attachment I want to actually download the attachment.
I've tried:
var message = inbox.GetMessage(uid, cancel.Token);
But this gets the entire message.
Also tried:
uids[0] = uid;
var ms = inbox.Fetch(uids, MessageSummaryItems.BodyStructure , cancel.Token);
var bp1 = inbox.GetBodyPart(uid, ms.First().Body, cancel.Token);
But again this downloads the attachment.
With your sample code, you are downloading the entire message because you are requesting the top-level body part of the message.
MIME is a tree structure of "body parts". What you want to do is to traverse the ms.First().Body to find the part(s) that you want, and then download them individually using the GetBodyPart() method.
Take a look at MailKit.BodyPartMultipart, MailKit.BodyPartMessage, MailKit.BodyPartBasic and MailKit.BodyPartText.
A BodyPartMultipart contains other body parts.
A BodyPartMessage parts contains a message (which will also contain a body part).
A BodyPartBasic is a basic leaf-node body part - usually an "attachment".
A BodyPartText is a text part (a subclass of BodyPartBasic) which can either be an attached text part or what you might consider to be the main text of the message.
To figure out if a BodyPartBasic is meant to be displayed inline or as an attachment, what you need to do is:
if (part.ContentDisposition != null && part.ContentDisposition.IsAttachment)
// it is an attachment
else
// it is meant to be shown to the user as part of the message
// (if it is an image, it is meant to be displayed with the text)
I should probably add a convenience property to BodyPartBasic called IsAttachment to make this a bit simpler (I'll try to add it today).
Hope that helps.
Update: I've just added the BodyPartBasic.IsAttachment convenience property in git master, so the next release of MailKit will have it.
This IMAP command will return just the text body.
a1 uid fetch <uid> (body.peek[text])
-Rick

Save Image to word of HTML reference

I export data from my database to word in HTML format from my web application, which works fine for me , i have inserted image into record,
the document displays the image also , all works fine for me except when i save that file and send to someone else .. ms word will not find link to that image
Is there anyway to save that image on the document so path issues will not raise
Here is my code : StrTitle contains all the HTML including Image links as well
string strBody = "<html>" +
"<body>" + strTitle +
"</body>" +
"</html>";
string fileName = "Policies.doc";
//object missing = System.Reflection.Missing.Value;
// You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Write(strBody);
You can create your html img tag with the image data encoded with base64. This way the image data is contained in the html document it self.
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
You images are probably only available via filesystem (i.e. their src starts with file).
There are a few ways
Make the image available via the internet: make sure their src starts with http and that they are hosted on a web server visible to the downloader (for example, the same server from which they are dowonloading the image)
Use a library, for example see NuGet
You can inline the images as #DevZer0 suggests.
Based on experience
Is the simplest to implement but has some annoyances (the server needs to be available to the user)
Is probably the best way if you do a lot of Word or Office files manipulation.
Can be done and it would solve the problem, although you wouldn't have a full library to support further use cases.
Use a word document creation library if you really want to have flexibility in creating doc or docx type files. Like all other popular document formats, the structure needs to be accurate enough for the program that opens up the documents. Like you obviously cannot create a PDF file just by setting content type "application/PDF", if your content is not in a structure that PDF reader expects. Content type would just make the browser identify the extension (incorrectly in this case) and download it as a PDF, but its actually simple text. Same goes for MS word or any other format that requires a particular document structure to be parsed and displyed properly.
Since every picture, table is of type shape in Word/Excel/Powerpoint, you could simply add with your program an AlternativeText to your picture, which would actually save a URL of the download URL and when you open, it will retrieve its URL and replace it.
foreach (NetOffice.WordApi.InlineShape s in docWord.InlineShapes)
{
if (s.Type==NetOffice.WordApi.Enums.WdInlineShapeType.wdInlineShapePicture && s.AlternativeText.Contains("|"))
{
s.AlternativeText=<your website URL to download the picture>;
}
}
This would be the C# approach, but would require more time for the picture. If you write a small software for it, which replaces all pictures which contain a s.AlternativeText, you could replace a lot of pictures at same time.
NetOffice.WordApi.InlineShape i=appWord.ActiveDocument.InlineShapes.AddPicture(s.AlternativeText, false, true);
It will look for the picture at that location.
You can do that for your whole document with the 1 loop I wrote you. Means, if it is a picture and contains some AlternativeText, then inside you loop you use the AddPicture function.
Edit: Anoter solution, would be to set a hyperlink to your picture, which would actually go to a FTP server where the picture is located and when you click on the picture, it will open it, means he can replace it by himself(bad, if you have 200 pictures in your document)
Edit according Clipboard:
string html = Clipboard.GetText(TextDataFormat.Html);
File.WriteAllText(temporaryFilePath, html);
NetOffice.WordApi.InlineShape i=appWord.ActiveDocument.InlineShapes.AddPicture(temporaryFilePath, false, true);
The Clipboard in Word is capable to transform a given HTML and when you paste it to transform that table or picture into Word. This works too for Excel, but doesn't for Powerpoint. You could do something like that for your pictures and drag and drop from your database.

How to open .eml files in the WebBrowser control?

I'd like to ask here, how can I open a .eml file, located in the file system, in a WebBrowser control. Here's what I've at this moment:
string uri = Convert.ToString(myDataReader["Uri"]); //obtained the URI from a database query a few lines of code earlier
FileInfo file = new FileInfo(uri);
OpenPop.Mime.Message mensagem = OpenPop.Mime.Message.Load(file);
origem = mensagem.Headers.From.ToString(); //origin of the email
destino = mensagem.Headers.To.ToString(); //destiny
assunto = mensagem.Headers.Subject.ToString(); //subject
conteudo = mensagem.MessagePart.Body; //message body
I'm using OpenPop.Net to get the messages from the POP3 server in another form, and I need to know how to get the HTML part of those messages...
Thanks in advance!
João Borrego
Have you checked out the examples for OpenPop.Net? Specifically you should check out the "Find specific parts of an email (text, html, xml)" example.
There is a introduction to how email works on the website as well. This might be helpful in understanding how OpenPop.Net is built since it evolves around how emails are structured internally.

Categories