Hey there, fellow developer! Ready to supercharge your email game? Let's dive into Mailgun - the email service provider that's got your back for all things transactional and marketing emails. We'll be using the nifty mailgun.js package to make our lives easier. Buckle up!
Before we jump in, make sure you've got:
Let's get this party started:
mkdir mailgun-integration && cd mailgun-integration npm init -y npm install mailgun.js
Time to bring Mailgun into the mix:
const formData = require('form-data'); const Mailgun = require('mailgun.js'); const mailgun = new Mailgun(formData); const mg = mailgun.client({ username: 'api', key: process.env.MAILGUN_API_KEY || 'your-api-key-here' });
Let's send that email, shall we?
mg.messages.create('your-domain.com', { from: "Excited User <[email protected]>", to: ["[email protected]"], subject: "Hello from Mailgun!", text: "Testing some Mailgun awesomeness!" }) .then(msg => console.log(msg)) // logs response data .catch(err => console.log(err)); // logs any error
Want to level up? Try these:
const attachment = new formData(); attachment.append('attachment', fs.createReadStream('path/to/file.pdf')); mg.messages.create('your-domain.com', { // ... other message options attachment: attachment })
mg.messages.create('your-domain.com', { // ... other message options template: "your-template-name", 'h:X-Mailgun-Variables': JSON.stringify({name: "John Doe"}) })
Always be prepared:
mg.messages.create('your-domain.com', messageData) .then(response => { console.log(response.status, response.message); // Handle successful send }) .catch(error => { console.error('Error:', error.message); // Handle the error appropriately });
Don't forget to test:
const mg = mailgun.client({ username: 'api', key: process.env.MAILGUN_API_KEY, url: 'https://api.mailgun.net' // Use this for testing });
And there you have it! You're now a Mailgun integration wizard. Remember, practice makes perfect, so keep experimenting and building awesome stuff. Happy coding!