Basic question here: I'm sending emails using the default SmtpClient of the .NET framework (3.5). The bodytype is HTML (IsBodyHtml = true) In the body I've added a url with two parameters in the querystring like so:
http://server.com/page.aspx?var1=foo&var2=bar
This get's encoded to:
http://server.com/page.aspx?var1=foo%26var2=bar (the ampersand is encoded as percent-26)
When doing a simple Request["var2"] I get 'null'.
What should I do to properly encode the ampersand in the mail message?
This works fine for me:
var client = new SmtpClient();
client.Host = "smtp.somehost.com";
var message = new MailMessage();
message.From = new MailAddress("from#example.com");
message.To.Add(new MailAddress("to#example.com"));
message.IsBodyHtml = true;
message.Subject = "test";
string url = HttpUtility.HtmlEncode("http://server.com/page.aspx?var1=foo&var2=bar");
message.Body = "<html><body>Test</body></html>";
client.Send(message);
Use the UrlEncode method. This will do all the encoding of your input string for you.
Related
I am trying to read a multi line txt document and trying to send an email message with the same multi line content as in the text document using c#
I tried using the File.ReadAllText method but that reads the entire txt document content in one string and puts it in the email body without the line separation.
Let's say a txt doc has the following lines
a
bcd
efgh
I want the mail message to be sent in the same format.
Code Specific to Send email is,
mail.IsBodyHtml = true;
mail.Body = File.ReadAllText(path);
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "abc";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.DeliveryMethod = system.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("", "");
}
smtp.Send(mail);
Please, use StreamReader instance with ReadLine() method to read document line by line. Also you can use newline separator to format your document in right way.
I've found this link on how to using Razor Engine for email templates in asp.net and it worked great. But I've tried to have a logo in the email template with an image.
Something like this:
EmailTemplate.cshtml (this by the way is a strongly-type view)
<html>
<body>
<img src="logo.jpg" />
</body>
</html>
and when I try to submit it on email, it seems that the image path was not read, it only rendered an X in the content.
I'm thinking to pass the image path as part of the Model but it seems odd that way. Is there any way to achieve this?
Any help would be much appreciated. Thanks
To see image everywhere you can use these options:
Absolute Url
You can simply use full absolute path of image for example "http://example.com/images/logo.png"
IMO It is the most simple option and recommended for your problem.
Attachment
As mentioned by Mason in comments You can attach image to mail and then put image tag and useContentId of attachment:
//(Thanks to Mason for comment and Thanks to Bartosz Kosarzyck for sample code)
string subject = "Subject";
string body = #"<img src=""$CONTENTID$""/> <br/> Some Content";
MailMessage mail = new MailMessage();
mail.From = new MailAddress("from#example.com");
mail.To.Add(new MailAddress("to#example.com"));
mail.Subject = subject;
mail.Body = body;
mail.Priority = MailPriority.Normal;
string contentID = Guid.NewGuid().ToString().Replace("-", "");
body = body.Replace("$CONTENTID$", "cid:" + contentID);
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
//path of image or stream
LinkedResource imagelink = new LinkedResource(#"C:\Users\R.Aghaei\Desktop\outlook.png", "image/png");
imagelink.ContentId = contentID;
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imagelink);
mail.AlternateViews.Add(htmlView);
SmtpClient client = new SmtpClient();
client.Host = "mail.example.com";
client.Credentials = new NetworkCredential("from#example.com", "password");
client.Send(mail);
Data Uri
you can use data uri (data:image/png;base64,....).
Not Recommended because of weak support in most of mail clients, I tested it with Outlook.com(web) and OutlookWebAccess(web) and Office Outlook(Windows) and Outlook(windows 8.1) and unfortunately it worked only on OutlookWebAccess(web).
I have an application that performs some tests. As a result of these tests an XML object is produced (from an XmlDiff compare).
Is there any way to embed the XML into an Email body in a formatted state?
I am using XmlWriter to a StringBuilder object then converting the string into and "html safe" format using System.Security.SecurityElement.Escape(). In the MailMessage, I set IsBodyHtml = true.
To extract the XML I want to embed:
public static string GetDiff(string approvedfile, string failingfile)
{
StringBuilder sb = new StringBuilder();
XmlWriter xmlwriter = XmlWriter.Create(sb);
XmlDiff xdiff =
new XmlDiff(XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreNamespaces |
XmlDiffOptions.IgnorePrefixes);
bool response = xdiff.Compare(approvedfile, failingfile, false, xmlwriter);
xmlwriter.Flush();
xmlwriter.Close();
return System.Security.SecurityElement.Escape(sb.ToString());
}
To set the body content I am using:
string sb = GetDiff(approvedMapfile, fileout);
string message = String.Format("Comparison of Map item1 and Map item2 for {0} failed.</br>Review the differences here:</br>{1}</br> and Compare the files</br>{2}</br>and</br>{3}</br>to find the differences.", loc, sb, emailApprovedMap, emailFailedMap);
Util.SendStatusEmail(message);
in SendStatusEmail the mail information is being set thusly:
public static string SendStatusEmail(string status)
{
string hostServer = "smtphost.this.server.com";
MailMessage mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = hostServer;
client.Credentials = CredentialCache.DefaultNetworkCredentials;
MailAddress from = new MailAddress("me#here.com", "Me There");
mail.From = from;
mail.To.Add("You#there.com");
mail.IsBodyHtml = true;
mail.Body = status;
mail.Subject = "Map Checker status report";
try
{
client.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return string.Empty;
}
When the email is received using the above methodology, the embedded XML is included, but it is not formatted, it appears as one long string of XML.
Is there a way to programmatically embed XML in an email body and have it appear as formatted?
Thanks for your help!
I found solution, in the last of the body message create one div and set style display none, not insert close div only open tag div with style display none.
mail.IsBodyHtml = false;
does the job, unless you really need html formatted body.
Maybe is too old but i have solution to just encode the xml text.
refer how to do on C#: How to encode the ampersand if it is not already encoded?
Basically having lib to do this:
HttpUtility.HtmlEncode(string)
i'm doing with java something like this:
StringEscapeUtils.escapeHtml4("<xml><row>1</row></xml>");
Im trying to set the mail message body of an html email to a different language im using
MailMessage msg = new MailMessage();
msg.BodyEncoding = Encoder ?????
thanks
Look to this info: http://en.wikipedia.org/wiki/UTF-8
As #SriramSakthivel mention in his comment you can do it:
UTF-8 Encoding support all language what you need!
MailMessage message = new MailMessage()
{
From = new MailAddress("My#MyMail.com", "Test"),
BodyEncoding = Encoding.UTF8,
Body = body,
IsBodyHtml = true,
ReplyTo = new MailAddress("Someone#Test.com"),
SubjectEncoding = Encoding.UTF8
}
The encoding is not about language, but about character set. C# uses UTF16 internally, so if you set your encoding to UTF, you should be able to write any text you want as UTF can express any character of any set. That's what UNICODE is used for.
I'd like to send email by asp.net . I use this code and it is work fine.
mail.From = new MailAddress("mail#gmail.com", "sender", System.Text.Encoding.UTF8);
string to = Session["Umail"].ToString();
mail.To.Add(to);
mail.IsBodyHtml = true;
mail.SubjectEncoding = Encoding.UTF8;
mail.BodyEncoding = Encoding.GetEncoding("utf-8");
mail.Subject = "subject";
mail.Body = "body" ;
SmtpClient smtp = new SmtpClient("Smtp.gmail.Com", 587);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("mail#gmail.com", "pass"); smtp.Send(mail);
But I'd like a custom and beautiful mail. Like emails that send from facebook, google team and etc. I know that can use html tag in mail.Body but is it good way? What is the best way ?
This is ready to use code snippet which I use for sending email which contains both text content and the content based on a html template:
// first we create a plain text version and set it to the AlternateView
// then we create the HTML version
MailMessage msg = new MailMessage();
msg.From = new MailAddress("from#email", "From Name");
msg.Subject = "Subject";
msg.To.Add("to#email");
msg.BodyEncoding = Encoding.UTF8;
String plainBody = "Body of plain email";
//first we create the text version
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
msg.AlternateViews.Add(plainView);
//now create the HTML version
MailDefinition message = new MailDefinition();
message.BodyFileName = "~/MailTemplates/template1.htm";
message.IsBodyHtml = true;
message.From = "from#email";
message.Subject = "Subject";
//Build replacement collection to replace fields in template1.htm file
ListDictionary replacements = new ListDictionary();
replacements.Add("<%USERNAME%>", "ToUsername");//example of dynamic content for Username
//now create mail message using the mail definition object
//the CreateMailMessage object takes a source control object as the last parameter,
//if the object you are working with is webcontrol then you can just pass "this",
//otherwise create a dummy control as below.
MailMessage msgHtml = message.CreateMailMessage("to#email", replacements, new LiteralControl());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");
//example of a linked image
LinkedResource imgRes = new LinkedResource(Server.MapPath("~/MailTemplates/images/imgA.jpg"), System.Net.Mime.MediaTypeNames.Image.Jpeg);
imgRes.ContentId = "imgA";
imgRes.ContentType.Name = "imgA.jpg";
imgRes.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imgRes);
msg.AlternateViews.Add(htmlView);
//sending prepared email
SmtpClient smtp = new SmtpClient();//It reads the SMPT params from Web.config
smtp.Send(msg);
and these are key parts of the html template:
<p>Username: <%USERNAME%></p>
<img src="cid:imgA"/>
I'd like a custom and beautiful mail.
I know that can use html tag in mail.Body but is it good way? What is
the best way ?
I don't know exactly what is that supposed to mean, but generally, there are two ways to do it. (If we talking about images or sources in email etc..)
You can use LinkedResource class of .NET Framework.
Represents an embedded external resource in an email attachment, such
as an image in an HTML attachment.
Alternatively, and more simply in my opinion, if you want to use some images in your email, put the image in a public location then just reference that location in the HTML of the email.