Send url with querystring with SmtpClient
-
21-09-2019 - |
Question
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?
Solution
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><a href=\"" + url + "\">Test</a></body></html>";
client.Send(message);
OTHER TIPS
Use the UrlEncode method. This will do all the encoding of your input string for you.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow