Created
April 1, 2025 10:21
-
-
Save heitara/1d2d94e28755dbc664bacd7529a329e2 to your computer and use it in GitHub Desktop.
Mailgun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// import Mailgun from 'mailgun.js'; | |
// import formData from 'form-data'; | |
const formData = require('form-data'); | |
const Mailgun = require('mailgun.js'); | |
// Mailgun configuration | |
const apiKey = ''; | |
const domain = 'domain.com'; | |
const fromEmail = 'help@' + domain; | |
const mailgun = new Mailgun(formData); | |
// Initialize Mailgun client | |
// provide url if used from EU | |
const mg = mailgun.client({username: 'username', key: apiKey, url: 'https://api.eu.mailgun.net'}); | |
/** | |
* Send an email using Mailgun | |
* @param {string} to - Recipient email address | |
* @param {string} subject - Email subject | |
* @param {string} text - Plain text email body | |
* @param {string} html - HTML email body (optional) | |
* @param {Array} attachments - Array of file paths to attach (optional) | |
* @returns {Promise} - Promise resolving to Mailgun response | |
*/ | |
async function sendEmail(to, subject, text, html = null, attachments = []) { | |
try { | |
// Prepare email data | |
const messageData = { | |
from: fromEmail, | |
to: to, | |
subject: subject, | |
text: text | |
}; | |
// Add HTML if provided | |
if (html) { | |
messageData.html = html; | |
} | |
// Add attachments if provided | |
if (attachments.length > 0) { | |
messageData.attachment = attachments.map(filePath => { | |
return fs.createReadStream(filePath); | |
}); | |
} | |
// Send the email | |
const result = await mg.messages.create(domain, messageData); | |
console.log('Email sent successfully:', result); | |
return result; | |
} catch (error) { | |
console.error('Error sending email:', error); | |
throw error; | |
} | |
} | |
// Example usage | |
async function main() { | |
try { | |
// Simple text email | |
await sendEmail( | |
'[email protected]', | |
'Hello from Mailgun', | |
'This is a test email sent from Node.js using the latest Mailgun SDK.' | |
); | |
console.log('All emails sent successfully!'); | |
} catch (error) { | |
console.error('Failed to send email:', error); | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment