Hesperus
Hesperus

Reputation: 113

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:[email protected]?subject={HttpUtility.UrlEncode(subject)}&body={HttpUtility.UrlEncode(yourMessage)}"; 

     Process.Start(url);
     }

Upvotes: 1

Views: 1033

Answers (1)

NineBerry
NineBerry

Reputation: 28499

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:[email protected]?subject={Uri.EscapeDataString(subject)}&body={Uri.EscapeDataString(yourMessage)}";
}

Upvotes: 2

Related Questions