Convert SMTP Client Mail message to HTML - c#

I have an issue with an mvc4 application in witch i would like to send a generated html page created with HTML + C#. The problem is that when i recieved the email i see my c# code like the exemple bellow:
Recieved Email
But in the mail preview i can see the correct values like this:
Mail Preview
So this is my EmailTemplate method:
<pre>
public static async Task<string> EMailTemplate (string template)
{
var templateFilePath =HostingEnvironment.MapPath("~/Views/Home/") + template + ".cshtml";
StreamReader objstreamreaderfile = new StreamReader(templateFilePath);
var body = await objstreamreaderfile.ReadToEndAsync();
objstreamreaderfile.Close();
return body;
}
</pre>
Please if you have any idea how to convert my template to Html without inclouding my C# code.
Thanks,

Use Pure Html template (Not a cshtml view) with Inline CSS and Absolute image URIs for email body and fill it text templates. See the below image.
In the above image, field with ##...## are text templates.
Now read this HTML template as a string and replace ##...## fields by some dynamic information using the C# code (Actually any language code). You can use string.Replace() method to replace these fields by actual values. I have already used this method and it is working fine. I hope this will help you too.

Related

Using X-ALT-DESC / Applying HTML to calendar invites in Outlook

I'm a beginner in C# (and any networking code to be honest). I'm trying to send a calendar invite, that will be wired when you click a button on the company's website. This is a typical n-tier system, using asp.net/C# and SQL.
We used to simply generate an ics that the user would then have to know to open with Outlook, but I've since learned how to manually code a VCALENDAR so it shows up right away in Outlook nice and neat.
It's all been going fairly smoothly, but I would now like the body of the calendar invite to be able to accept HTML, to attach links in particular. I've experimented with AlternateViews, but it seems that the "X-ALT-DESC" attribute inside of VCALENDAR should do exactly what I want. However, try as I may Outlook ignores it and uses the description. There is clearly something I am missing.
(To clarify, everything works & compiles, except for the HTML alt description)
private Guid? CreateEmail()
{
Guid eventGuid = Guid.NewGuid();
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.From = new MailAddress("fromemail", "From Name");
msg.To.Add(toEmail);
msg.Subject = subject;
StringBuilder s = new StringBuilder();
s.AppendLine("BEGIN:VCALENDAR");
s.AppendLine("VERSION:2.0");
s.AppendLine("PRODID:-//My Product//Outlook MIMEDIR//EN");
s.AppendLine("METHOD:" + method); //In this case, "REQUEST"
s.AppendLine("STATUS:" + status.status); //"CONFIRMED"
s.AppendLine("BEGIN:VEVENT");
s.AppendLine("UID:" + eventGuid.ToString());
s.AppendLine("PRIORITY" + status.priority); //3
s.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:" + ShowAs.ToString()); //"BUSY"
s.AppendLine("SEQUENCE:" + UpdateNumber);//0
s.AppendLine("DTSTAMP:" + DateTime.Now.ToUniversalTime().ToString());
s.AppendLine("DTSTART:" + DateTimetoCalTime(startTime));
s.AppendLine("DTEND:" + DateTimetoCalTime(endTime));
s.AppendLine("SUMMARY:" + subject);
s.AppendLine("LOCATION: " + location);
s.AppendLine("DESCRIPTION: " + "Plain simple description"
string html_begin = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">" +
"\n<html>" +
"\n<head>" +
"\n<title></title>" +
"\n</head>" +
"\n<body>" +
"\n<!-- Converted from text/rtf format -->\n\n<P DIR=LTR><SPAN LANG=\"en-us\">" +
"\n<Font face=\"Times New Roman\"";
body = "I simply <b> want some bold </b> here 555";
string html_end = "</font></span></body>\n</html>";
string html_body = html_begin + body + html_end;
msg.Body = html_body;
s.AppendLine("X-ALT-DESC;FMTTYPE=text/html:" + html_body);
msg.Body = html_body;
s.AppendLine("X-ALT_DESC;FMTTYPE=text/html:" + html_body);
s.AppendLine("STATUS:" + status.status); //"CONFIRMED"
s.AppendLine("BEGIN:VALARM");
s.AppendLine("TRIGGER:-PT1440M");
s.AppendLine("ACTION:Accept");
s.AppendLine("DESCRIPTION:Reminder");
s.AppendLine("END:VALARM");
s.AppendLine("END:VEVENT");
s.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address));
s.AppendLine("END:VCALENDAR");
System.Net.Mime.ContentType type = new System.Net.Mime.ContentType("text/calendar");
type.Parameters.Add("method", method);
type.Parameters.Add("name", "meeting.ics");
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(s.ToString(), type));
SMTP.send(msg);
return EventGuid;
Produces this body in outlook:
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 3.2//EN”>
<html>
<head>
<title></title>
</head>
<body>
<!-- Converted from text/rtf format -->
<P DIR=LTR><SPAN LANG=”en-us”>
<Font face=”Times New Roman”I simply <b> want some bold </b> here 555</font></span></body>
</html>
From testing:
If I leave Msg.body out, it just used the "DESCRIPTION".
If I make it equal the HTML, I get the above result.
Thank You!
You can have X-ALT-DESC on multiple lines, you just need to add a space on the beginning of each lines following it.
Lines of text SHOULD NOT be longer than 75 octets, excluding the line break. Long content lines SHOULD be split into a multiple line representations using a line "folding" technique. That is, a long line can be split between any two characters by inserting a CRLF immediately followed by a single linear white-space character (i.e., SPACE or HTAB). Any sequence of CRLF followed immediately by a single linear white-space character is ignored (i.e., removed) when processing the content type.
https://icalendar.org/iCalendar-RFC-5545/3-1-content-lines.html
I found that the HTML string must be all on one line. If the HTML is broken over multiple lines, that does not conform to Vcalendar encoding and the description is either rendered as a blank page or as plain text with all HTML tags visible.
I've seen others out there claiming that the DESCRIPTION tag must be used in front of "X-ALT-DESC;FMTTYPE=text/html:". This is totally WRONG and FALSE. If "DESCRIPTION" exists, it takes precedence, the "X-ALT-DESC;FMTTYPE=text/html:" line is completely ignored by Outlook and the plain text description is rendered. Therefore, "X-ALT-DESC;FMTTYPE=text/html:" must stand on it's own and be on it's own line.
Working example:
...
X-ALT-DESC;FMTTYPE=text/html:<html><body>Bing</body></html>
...
Wrong:
...
DESCRIPTION;X-ALT-DESC;FMTTYPE=text/html:<html><body>Bing</body></html>
...
Wrong again:
...
X-ALT-DESC;FMTTYPE=text/html:<html>
<body>
Bing
</body>
</html>
...
For those in the future:
The problem was the use of
.AppendLine.
Simply use
.Append
The ics file which i am loading is not created with proper spaces which is longer than 75 octets, if i am manually adding space and loading to Ical.net.Calendar it works fine. But i want to do the same through c# code like manipulating the calendar file before loading to avoid parsing errors.
For reference, here's an explanation from https://icalendar.org/
"The original iCalendar standard allowed only plain text as part of an event description. HTML markup, such as font attributes (bold, underline) and layout (div, table) was not allowed in the text description field. First seen in Microsoft Outlook, the X-ALT-DESC parameter provides a method to add HTML to an event description. "X-" fields are allowed for non-standard, experimental parameters. This field has become the method of choice when including HTML in a description. When using HTML, both fields must be included so that iCalendar readers that do not support the X-ALT-DESC field can still read the text version."
...and it looks like Outlook 2016 dropped support for this. Generating ics files with html description only is most of the time not an option as Thunderbird/Lightening in the past did not handle this leading to calendar invites with empty body.
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_outlook/outlook-2016-ics-description-shows-no-html/08d06cba-bfe4-4757-a052-adab64ea75a2?page=1

C# Winnovative HTML to PDF

I am searching for a solution to convert HTML to PDF with external CSS support. I downloaded the trial version of the Winnovative Toolkit Total v11.14, and tried out the demo application for the method public byte[] GetPdfBytesFromHtmlString (string htmlString, string urlBase). The PDF files are generated, but the CSS is not applied.
Note: I tried the same input HTML string and base URL in the demo site. It's working fine, so I don't know why it's not working in my system. The demo application is shared in v11.14 ZIP files.
Input provided for this method:
htmlString = HTML source of the url 'http://www.winnovative-software.com/'
urlBase = "http://www.winnovative-software.com/"
Are you using any proxy to access Internet? In this case you should set the HtmlToPdfConverter.ProxyOptions object properties in your code.

MailMessage class

I want to add an image into my mail, I have everything working for the most part but my only problem is that in order to have an image I need to set the body to HTML format... which then stops me from having break lines. So I think this is a 2 part question.
Is there a way to have both normal String for the first part of a message body and then the HTML for just the picture? or if not the How can I find and change the break line of a normal String to < br>?
I believe I need to change \n to < br/> in a normal String
body.Replace("\n", "< br/>);
doesn't seem to work...
Try this:
body = body.Replace(Environment.NewLine, "<br />");
the mail format actually is written in the header of the message so its either TEXTformat or HTML format, you cant mix them both in the same message
I am assuming you are using the Mail Libray in .net ? you will need to change your format type from text to HTML with the IsBodyHtml on the mail message
You can just create a html image and use AlternateView to then get the plain text
Sending a mail as both HTML and Plain Text in .net

Why url parameter doesn't have correct format in javascript?

I have to create a javascript which contains an url in code behind page using C#. But the url parameter inside javascript doesn't have correct format after generated by C#.
Example:
Url parameter: http://google.com
Javascript: javascript:dnnModal.show('http://google.com',false,365,206,false)
C# code:
string link = "http://google.com?popUp=true";
string googleIcon = "<a href='javascript:dnnModal.show('" + link +',false,365,206,false)'><img border='0' src='~/Icons/gIcon.png'></a>";
After generated from code behind the page view the url incorrect format. There is the code of googleIcon after I am using "View Select Source" to view the code of aspx page:
<img src="~/Icons/gIcon.png" border="0">
The hyperlink on icon just show this when I move the mouse over it:
javascript:dnnModal.show(
The url is lost and the remind string is lost too.
I need some help on my issue to show the way how to pass an url parameter into javascript using C#.
Should be like this,
string googleIcon = "<img border='0' src='~/Icons/gIcon.png'>";
You are not escaping the strings properly
string googleIcon = "<a href='javascript:dnnModal.show(\"" + link +"\",false,365,206,false)'><img border='0' src='~/Icons/gIcon.png'></a>";
I agree with two other answers, but you should try to encapsulate these kind of tasks in a user control maybe. but if that's not possible I suggest to use System.Web.UI.HtmlControls instead, since it will give you more flexibility.
Something like this:
HtmlLink myHtmlLink = new HtmlLink();
myHtmlLink.Href = #"javascript:dnnModal.show(\"" + link +"\",false,365,206,false)";
HtmlImage myImage = new HtmlImage();
myImage.Src = "~/Icons/gIcon.png";
myImage.Border = 0;
myHtmlLink.Controls.Add(myImage);
I like this approach more because Asp.net is responsible for creating DOM, which means that you will be safe and you're guaranteed to get a valid XHTML result.

Response.Write on Server Controls

I am creating a custom include method (load) to check if a file exists. The load function includes the file if it exists or sends an email to notify me of a broken link if it doesn't. The problem I am having is if the include file contains server controls, it just displays them as plain text. This is a problem if I were to try to add an include file to an include file.
In default.aspx I have:
<% ResourceMngr.load("~/Includes/menu.inc"); %>
In ResourceMngr:
public static void load(String url) {
string file = HttpContext.Current.Server.MapPath(url);
if (System.IO.File.Exists(file))
{
HttpContext.Current.Response.Write(System.IO.File.ReadAllText(file));
}
else
{
String body = "This message was sent to inform you that the following includes file is missing: \r\n";
body += "Referrer URL: " + HttpContext.Current.Request.Url.AbsoluteUri + "\r\n";
body += "File Path: " + file;
MailUtil.SendMail("email#email.com", "Missing Includes File", body);
}
}
So, if "menu.inc" also includes a <% ResourceMngr.load("~/Includes/test.inc"); %> tag, it just prints it out in plain text on the page instead of trying to include test.inc while all the other html on the page shows up exactly as expected. How would I allow my include file to have server controls?
I assume you come from a classic asp or php background. asp.net doesn't work in this way with includes. You probably want to look up some basic webforms or mvc tutorials because you want to work with the framework, and not against it :-)
in particular, look up how to use UserControls (ie. the ones with a .ascx extension)

Categories

Resources