mailjet / mailjet-apiv3-dotnet

[API v3] Official Mailjet API v3 .NET wrapper
https://dev.mailjet.com
MIT License
74 stars 31 forks source link

Sample code needed for sending attachments #59

Closed Razique closed 3 years ago

Razique commented 3 years ago

Hi, the current documentation does not contain any indication on how to attach a file to an email.

Any guidance would be appreciated :)

Razique commented 3 years ago

Update, per the official API documentation, we only need to add a new Attachments item to the request body.

MailjetRequest request = new MailjetRequest { Resource = Send.Resource, }.Property(
    Send.Messages,
    new JArray {
        new JObject {
            {
                "From",
                new JObject {
                    { "Email", "me@me.com" },
                    { "Name", "Me" }
                }
            },
            {
                "To",
                new JArray {
                    new JObject {
                        { "Email", "you@you.com" },
                        { "Name", "You" }
                    }
                }
            },
            { "Subject",  "Mailjet Email!" },
            { "TextPart", "Hello World!" },
            {
                "HTMLPart",
                "Test email"
            },
            {
                "Attachments",
                new JArray
                {
                    new JObject
                    {
                        { "ContentType","text/plain" },
                        { "Filename", "test.txt" },
                        { "Base64Content", emailAttachementB64 }
                    }
                }
            }
        }
    }
);

Notice that per the API documentation, the email Attachment must be a Base64 representation of the string.

You can write the following helper to convert the string:

public static string Base64Encode(string plainText) {
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);

    return System.Convert.ToBase64String(plainTextBytes);
}

If the file is in a binary format, you can use the File.ReadAllBytes method that returns a bytes array.

sdiakovskyi-gd commented 3 years ago

@Razique Hi!

Thanks for pointing out I see you already found a solution, but just in case - besides guides, MailJet has API reference for each method with examples in different languages. C# with attachments and inline attachments code is also there :-)