6

I'm using RestSharp to try and send an attachment with the Mailgun API. I have tried attaching from both a file in the system using a hardcoded path and also from a binary file stored in the database using ToArray() method on the varbinary(MAX) (SQL Server) property both with no success.

The attachment technically sends, but when the email arrives in my inbox the file size is always roughly 302bytes big and is always corrupt. I have tried 3 different files and get the same problem each time.

The rest of the email sends, delivers and displays fine. It's just the attachments that are broken.

Breakdown of code:

// Doesnt work(Data property is varbinary(MAX)
request.AddFileBytes("attachment",databaseModel.Data.ToArray(),databaseModel.Filename, "multipart/form-data");

// Also doesnt work(Data property is varbinary(MAX)
request.AddFile("attachment",databaseModel.Data.ToArray(),databaseModel.Filename, "multipart/form-data");

// Also doesnt work        
var path = @"D:\Template.pdf";
request.AddFile("attachment",path,"multipart/form-data");
Jamie Kitson
  • 3,973
  • 4
  • 37
  • 50
Sinmok
  • 656
  • 1
  • 10
  • 19

2 Answers2

17

This code works:

public static void Main(string[] args)
{
    Console.WriteLine(SendSimpleMessage().Content.ToString());
    Console.ReadLine();
}

public static IRestResponse SendSimpleMessage()
{
    var path1 = @"C:\Users\User\Pictures\website preview";
    var fileName = "Learn.png";
    RestClient client = new RestClient();
    client.BaseUrl = new Uri("https://api.mailgun.net/v3");
    client.Authenticator =
        new HttpBasicAuthenticator("api",
                                    "key-934345306fead7de0296ec2fb96a143");
    RestRequest request = new RestRequest();
    request.AddParameter("domain", "mydomain.info", ParameterType.UrlSegment);
    request.Resource = "{domain}/messages";
    request.AddParameter("from", "Excited User <example@mydomain.info>");
    request.AddParameter("to", "peter.cech@gmail.com");        
    request.AddParameter("subject", "Hello");
    request.AddParameter("text", "Testing some Mailgun awesomness! This is all about the text only. Just testing the text of this email.";
    request.AddFile("attachment", Path.Combine(path1,fileName));
    request.Method = Method.POST;
    return client.Execute(request);
}
AlexGH
  • 2,735
  • 5
  • 43
  • 76
6

I figured it out..

Not supposed to add "multipart/form-data" on the request.AddFile();

Removing this fixes the problem.

Sinmok
  • 656
  • 1
  • 10
  • 19
  • I tried using - request.AddFile("attachment", Path.Combine(path1,fileName), "multipart/form-data") and it is working fine. Thanks - @Sinmok – Gobind Gupta Nov 26 '19 at 06:51