Question

I wonder if you can help me to add MemoryStream attachment object for the email attachment using RestSharp?

Here is the code that I got from MailGun but it is attaching a physical file in this example:

Thank you.

public static IRestResponse SendComplexMessage() {
       RestClient client = new RestClient();
       client.BaseUrl = "https://api.mailgun.net/v2";
       client.Authenticator =
               new HttpBasicAuthenticator("api",
                                          "key-3ax6xnXXXXXXXX");
       RestRequest request = new RestRequest();
       request.AddParameter("domain",
                            "samples.mailgun.org", ParameterType.UrlSegment);
       request.Resource = "{domain}/messages";
       request.AddParameter("from", "Excited User <me@samples.mailgun.org>");
       request.AddParameter("to", "foo@example.com");
       request.AddParameter("cc", "baz@example.com");
       request.AddParameter("bcc", "bar@example.com");
       request.AddParameter("subject", "Hello");
       request.AddParameter("text", "Testing some Mailgun awesomness!");
       request.AddParameter("html", "<html>HTML version of the body</html>");

// I need to add memorystream object here ---
       request.AddFile("attachment", Path.Combine("files", "test.jpg"));
       request.AddFile("attachment", Path.Combine("files","test.txt"));
// -------------------------------------------

       request.Method = Method.POST;
       return client.Execute(request);
}
Was it helpful?

Solution

Easy enough. Use the overload that takes the file as a byte array. Assuming

using(var memoryStream = new MemoryStream(File.ReadAllBytes("test.jpg")))

or similar somewhere above, all you need to do is

request.AddFile("attachment", memoryStream.ToArray(), "test.jpg");    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top