title: Email Attachments in HttpClient
body: <p>I'm currently using Mailgun to perform some email sending within my app via their REST API services. Their examples use RestSharp which having already got a the MS Web API rest client in my project, I'm reluctant to install another for this functionality. Standard emails work fine using HttpClient however when it comes to add an attachment I'm slightly at a loss.</p>
  
  <p>There code is as follows for sending an email with an attachment...</p>
  
  <pre><code>RestClient client = new RestClient();
  
  client.BaseUrl = new Uri("https://api.mailgun.net/v3");
  client.Authenticator = new HttpBasicAuthenticator("api", "MailgunKeyGoesHere");
  RestRequest request = new RestRequest();
  request.AddParameter("domain",
                 "mailgundomain.mailgun.org", ParameterType.UrlSegment);
  request.Resource = "{domain}/messages";
  request.AddParameter("from", "Mailgun Sandbox &lt;postmaster@mailgundomain.mailgun.org&gt;");
  request.AddParameter("to", "My Email &lt;myemail@testdomain.co.uk&gt;");
  request.AddParameter("subject", "Hello");
  request.AddParameter("text", "This is the test content");
  
  request.AddFile("attachment", Path.Combine("C:\\temp", "test.jpg"));
  
  request.Method = Method.POST;
  client.Execute(request);
  </code></pre>
  
  <p>This works fine as I tested this running in Linqpad. My code however doesn't an I can't seem to see what to do.</p>
  
  <pre><code>var client = new HttpClient();
  
  client.BaseAddress = new Uri(string.Format("{0}/{1}/messages", @"https://api.mailgun.net/v3", "mailgundomain.mailgun.org"));
  client.DefaultRequestHeaders.Accept.Clear();
  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "MailgunKeyGoesHere");
  
  var kvpContent = new List&lt;KeyValuePair&lt;string, string&gt;&gt;
  {
     new KeyValuePair&lt;string, string&gt;("Content-Disposition: form-data; name=\"from\"", "Mailgun Sandbox &lt;postmaster@mailgundomain.mailgun.org&gt;"),
     new KeyValuePair&lt;string, string&gt;("Content-Disposition: form-data; name=\"subject\"", "Test Email"),
     new KeyValuePair&lt;string, string&gt;("Content-Disposition: form-data; name=\"text\"", "It Worked!!"),
     new KeyValuePair&lt;string, string&gt;("Content-Disposition: form-data; name=\"to\"", "My Email &lt;myemail@testdomain.co.uk&gt;"),
  };
  
  var fileData = File.ReadAllBytes(@"C:\Temp\test.jpg");
  
  //This is where it goes wrong. I know at the moment fileData.ToString() is wrong but this is the last thing I tried
  kvpContent.Add(new KeyValuePair&lt;string, string&gt;("Content-Disposition: form-data; name=\"attachment\"; filename=\"test.jpg\" Content-Type: application/octet-stream",
                    fileData.ToString()));
  
  
  var formContent = new FormUrlEncodedContent(kvpContent);
  
  var response = client.PostAsync(client.BaseAddress, formContent).Result;
  </code></pre>
  
  <p>Any Ideas?</p>