Search code examples
c#urlmailto

How to respect spaces when passing body to an mailto in C#


I've got a Template style page which build a mailto link to open a prebuilt email in the users default mail client

I realise that using URLencode by default will replace spaces with + ( and pathencode will replace with %20 ) - but is it possible to pass a body and subject to a mailto while respecting spaces in the content? - for example, in javascript using encodeURIComponent(yourMessage) will retain the spaces within the "yourmessage" variable

   private void SubmitEmail(object sender, RoutedEventArgs e)
    {
    string txt = "text that is an example";
    string rnt = "this is also an example";
    string PrioStr = "this is an example, of text that will come from a radio buttons contents";
    var yourMessage = txt;
    var subject =$"firstvariable:{Rnt}     secondvariable:{PrioStr}";

    var url =$"mailto:test@test.com.com?subject={HttpUtility.UrlEncode(subject)}&body={HttpUtility.UrlEncode(yourMessage)}"; 

     Process.Start(url);
     }
  • this is a conversion of something i've already built using javascript which works as expected in javascript but when applying the logic to C# it replaces spaces in the subject/body with '+' symbols

Solution

  • Use Uri.EscapeDataString, which will escape spaces as %20.

    private void SubmitEmail(object sender, RoutedEventArgs e)
    {
        string txt = "text that is an example";
        string rnt = "this is also an example";
        string PrioStr = "this is an example, of text that will come from a radio buttons contents";
        var yourMessage = txt;
        var subject =$"firstvariable:{Rnt}     secondvariable:{PrioStr}";
    
        var url = $"mailto:test@test.com.com?subject={Uri.EscapeDataString(subject)}&body={Uri.EscapeDataString(yourMessage)}";
    }