'Mailgun Attachment + Axios
I would like to send an attachment with Mailgun using react+axios.
Currently, I get an email with an attachment, but it is not named correctly (the name is ".") and if I rename it to a text file it contains the text "[object Object]". Do you have any idea how to solve this problem?
const form = new FormData();
const fs = require("fs");
form.append("from", "[email protected]");
form.append("to", "Bob <[email protected]>");
form.append("subject", "Test");
form.append("text", "Hello!!");
form.append("attachment", [{
filename: "example.txt",
data: fs.readFileSync(__dirname + "/text.txt", {
encoding: "utf8",
flag: "r"
})
}]);
const endpoint = "https://api.mailgun.net/v3/sandbox123.mailgun.org/messages";
await axios.post(endpoint, form, {
auth: {
username: "api",
password: process.env.MAILGUN_API_KEY
},
headers: { "Content-Type": "multipart/form-data" }
});
Solution 1:[1]
Two things:
- As per the mailgun docs when sending attachments you must use "multipart/form-data" encoding. Try:
await axios.post(endpoint, form, {
auth: {
username: "api",
password: process.env.MAILGUN_API_KEY
},
headers: { 'Content-Type': 'multipart/form-data' }
});
- Try putting your attachment object inside an array. I am not familiar with the mailgun API but I saw a couple examples where the attachments were inside an array, maybe even if there is a single attachment the API is still expecting it this way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pr0grara |