Reputation: 1677
I'm doing a Cloud Function in Firebase to send an email with mailgun following the documentation.
I'm using TypeScript and I can not find an example about how to set up the API KEY, DOMAIN and how to send the email at the end. All the examples I have found are in JavaScript.
Example in JavaScript:
var API_KEY = 'YOUR_API_KEY';
var DOMAIN = 'YOUR_DOMAIN_NAME';
var mailgun = require('mailgun-js')({apiKey: API_KEY, domain: DOMAIN});
const data = {
from: 'Excited User <[email protected]>',
to: '[email protected], [email protected]',
subject: 'Hello',
text: 'Testing some Mailgun awesomeness!'
};
mailgun.messages().send(data, (error, body) => {
console.log(body);
});
TypeScript:
const API_KEY = 'YOUR_API_KEY';
const DOMAIN = 'YOUR_DOMAIN_NAME';
import * as mailgun from 'mailgun-js';
// How to set up ?
// How to send the email ?
I have tried using ts-mailgun, a wrapper for sending emails, but, didn't work because of an error while deploying the function.
My goal is to configure mailgun correctly using TypeScript to send an email to a user.
Upvotes: 3
Views: 2410
Reputation: 21
This question is from over a year ago, but after inspecting the linked GitHub page in the @types/mailgun-js
page here:
You can see the ConstructorParams interface, and see where it is called. It looks like you need to instantiate mailgun
like below. After doing this, the types started working for me.
import mg from 'mailgun-js';
const api_key = process.env.MG_API_KEY as string;
const DOMAIN = process.env.MG_DOMAIN as string;
const mailgun = new mg({apiKey: api_key, domain: DOMAIN});
const UsersMailList = mailgun.lists(process.env.USERS_LIST as string);
Upvotes: 2
Reputation: 29
npm i ts-mailgun
then:
import { NodeMailgun } from 'ts-mailgun';
const mailer = new NodeMailgun();
mailer.apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // Set your API key
mailer.domain = 'mail.my-sample-app.com'; // Set the domain you registered earlier
mailer.fromEmail = '[email protected]'; // Set your from email
mailer.fromTitle = 'My Sample App'; // Set the name you would like to send from
mailer.init();
// Send an email to [email protected]
mailer
.send('[email protected]', 'Hello!', '<h1>hsdf</h1>')
.then((result) => console.log('Done', result))
.catch((error) => console.error('Error: ', error));
from the ts-mailgun documentation
Upvotes: 2