I’m working on an Azure Function in .NET Core and need to send emails with attachments. I’m using Mailgun and Httpclient, but I’m struggling to get the attachments to work properly.
Here’s what I’ve tried so far:
var formData = new MultipartFormDataContent();
formData.Add(new StringContent("Sender <[email protected]>"), "from");
formData.Add(new StringContent("[email protected]"), "to");
formData.Add(new StringContent("Test Email"), "subject");
formData.Add(new StringContent("Email body text"), "text");
var fileBytes = File.ReadAllBytes("path/to/file.pdf");
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "attachment",
FileName = "report.pdf"
};
formData.Add(fileContent);
var response = await httpClient.PostAsync("https://api.mailgun.net/v3/yourdomain.com/messages", formData);
response.EnsureSuccessStatusCode();
The email gets sent, but there’s no attachment. I’ve tried different ContentDisposition values like ‘inline’ and ‘attachment’, but nothing works. Any ideas on how to fix this?
I’ve encountered this issue before when working with Mailgun’s API. One thing that solved it for me was explicitly setting the Content-Type header for the entire MultipartFormDataContent. Try adding this line before sending the request:
formData.Headers.ContentType = MediaTypeHeaderValue.Parse(“multipart/form-data”);
Additionally, ensure you’re using the correct API endpoint for your domain. The URL should be specific to your Mailgun domain, not just the generic api.mailgun.net.
If these don’t work, you might want to check Mailgun’s documentation for any recent changes to their attachment handling process. They occasionally update their API, which can affect how attachments are processed.
I’ve dealt with this exact problem before, and I found that the issue often lies in how Mailgun handles the attachment’s content disposition. Here’s what worked for me:
Instead of setting the ContentDisposition on the fileContent, try adding it as a separate string content to the form data:
formData.Add(new StringContent(“attachment”), “Content-Disposition”);
Also, make sure you’re using the correct API key - Mailgun has different keys for different purposes. Double-check you’re using the ‘Private API Key’ and not the ‘Public Validation Key’.
If you’re still having trouble, you might want to consider using Mailgun’s official C# library. It abstracts away a lot of these low-level details and can make working with attachments much easier.
Lastly, don’t forget to encode your API key in Base64 when adding it to the Authorization header. This is a common oversight that can cause silent failures.
hey there! i’ve had similar issues. try adding the content type for your attachment:
fileContent.Headers.ContentType = new MediaTypeHeaderValue(“application/pdf”);
also, double-check your file path. sometimes that trips things up. hope this helps!