Setting up Mailgun with TypeScript on Firebase Cloud Functions

Currently, I am working on a Cloud Function within Firebase to integrate with Mailgun for sending emails, following the guidelines provided in the Mailgun documentation.

My challenge lies in implementing this functionality using TypeScript, as I have been unable to locate any examples demonstrating how to configure the API KEY, DOMAIN, and ultimately send the email. Most resources available only show examples in JavaScript.

Here is an 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 <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04696144776569746861772a6965d686d6c63636b6669692a69686e67616a23686569">[email protected]</a>>',
  to: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee888181ae8b968f839e828bc08d81898386878e89898b82">[email protected]</a>, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6705061527021f060a170b024904080a">[email protected]</a>',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomeness!'
};

mailgun.messages().send(data, (error, body) => {
  console.log(body);
});

And here's what it looks like in TypeScript:

const API_KEY = 'YOUR_API_KEY';
const DOMAIN = 'YOUR_DOMAIN_NAME';

import * as mailgun from 'mailgun-js';
// How do I set this up ?

// How can I send the email ?

Although I attempted to use the ts-mailgun package, which simplifies email sending tasks, I encountered issues when deploying the function due to errors.

Ultimately, my objective is to successfully configure Mailgun using TypeScript to effectively deliver emails to users.

Answer №1

npm install ts-mailgun

After installing, follow these steps:


import { NodeMailgun } from 'ts-mailgun';

const mailer = new NodeMailgun();
mailer.apiKey = 'YOUR_API_KEY_HERE'; // Enter your API key
mailer.domain = 'mail.my-sample-app.com'; // Enter the domain you registered earlier
mailer.fromEmail = 'your-email@example.com'; // Set your email address
mailer.fromTitle = 'My Sample App'; // Set the name you are sending from

mailer.init();

// Sending an email to sample@example.com
mailer
    .send('sample@example.com', 'Hello!', '<h1>Sample Message</h1>')
    .then((result) => console.log('Email sent successfully', result))
    .catch((error) => console.error('Error sending email: ', error));

Source: ts-mailgun documentation

Answer №2

Even though this question was asked more than a year ago, I took a look at the GitHub page linked in the @types/mailgun-js documentation here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/58081d555e64d07049d2da6115e5118240162c73/types/mailgun-js/index.d.ts#L18

Upon examining the ConstructorParams interface and its usage, it became apparent that initializing the mailgun object as shown below is necessary. Upon making this change, the types started functioning correctly 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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transitioning a JavaScriptIonicAngular 1 application to TypescriptIonic 2Angular 2 application

I am currently in the process of transitioning an App from JavaScript\Ionic\Angular1 to Typescript\Ionic2\Angular2 one file at a time. I have extensively researched various guides on migrating between these technologies, completed the A ...

Struggling with an issue in React and Bootstrap4 while developing an application with create-react-app

In my experience with Windows 10, I encountered two scenarios where I faced problems. The first scenario involved creating applications using the create-react-app command and installing it with npm i -g [email protected]. Scenario 1 I stopped the React s ...

Guide on incorporating Kendo UI typings into a TypeScript module

Currently, I am working with Kendo UI for React and TypeScript. My goal is to import the Kendo UI typings for TypeScript using a "typeof import". Following the guidance provided at https://docs.telerik.com/kendo-ui/third-party/typescript, I successfully i ...

Ways to manage an rxjs observable reaction that may potentially have no data?

Currently, I am working with Angular2 and Ionic2 using typescript and have a requirement to manage responses from the backend service. The response may either be empty with http status 200 or it could be a json object containing an error message property ...

Looking to implement nested routes in Angular to ensure that each component's view updates properly

app-routing.module.ts import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; import { BreadcrumbComponent } from './main-layout/breadcrumb/breadcrumb.component'; im ...

Error: THREE.MTLLoader cannot be instantiated 2.0

Previously, I posted a question regarding this issue: Uncaught TypeError: THREE.MTLLoader is not a constructor I was able to resolve it by modifying the three-mtl-loader file. However, since I plan to upload my work to GitHub later, I need to find a solut ...

How can I detect if a control value has been changed in a FormGroup within Angular 2? Are there any specific properties to look

I am working with a FormGroup that contains 15 editable items, including textboxes and dropdowns. I am looking to identify whether the user has made any edits to these items. Is there a specific property or method I can use to check if the value of any i ...

Utilizing the URL path name for data retrieval in Next.js 14 - A step-by-step guide

I'm currently developing a blog using AWS Amplify Gen 2 and GraphQL for a Next.js 14 project with TypeScript. As part of my application, I need to fetch specific data based on the URL path name. Here's how I've approached it: My approach in ...

Using TypeScript to Import Modules without Default Exports (CommonJS)

Can a module that is defined without a default export be imported using import module from 'module'; and then compiled to commonjs? An answer on Stack Overflow suggests that it might be possible with the use of the --allowSyntheticDefaultImports ...

Achieving the incorporation of multiple components within a parent component using Angular 6

Within parent.component.html The HTML code I have implemented is as follows: <button type="button" class="btn btn-secondary (click)="AddComponentAdd()">Address</button> <app-addresse *ngFor="let addres of collOfAdd" [add]="addres">< ...

The module '@ngmodule/material-carousel' could not be located

Having an issue with Angular 8 where I am encountering an error when trying to import the @ngmodule/material-carousel module. The specific error message is: Cannot find module '@ngmodule/material-carousel' Package.json "private": true, "depen ...

What is the best way to select types conditionally based on the presence of a property in another type?

To begin with, I have a specific desired outcome: type Wrapper<ID extends string> = { id: ID }; type WrapperWithPayload<ID extends string, Payload> = { id: ID, payload: Payload }; enum IDs { FOO = "ID Foo", BAR = "ID Bar", BAZ = "ID Baz ...

What are some ways to incorporate advanced/nested type variables when using arrow functions?

Is there a way to use "advanced/nested" type variables, similar to how T is utilized in this function declaration, when working with arrow functions? function wrapInObject<T>(key: string) { return (x: T) => ({ [key]: x }); } I attempted to ach ...

Incorporating an external module into your Angular application for local use

I currently have two projects: my-components, which is an Angular library, and my-showcase, an Angular app. Whenever I make changes or add a new component to my library, I commit it to a private git repository and publish it to a private npm registry. This ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

Ways to utilize a field from an interface as a type of index

interface Mapping { "alpha": (a: string) => void "beta": (b: number) => void } interface In<T extends keyof Mapping> { readonly type: T, method: Mapping[T] } const inHandlers: In<"alpha"> = { type ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

Exploring the possibilities with Rollbar and TypeScript

Struggling with Rollbar and TypeScript, their documentation is about as clear as AWS's. I'm in the process of creating a reusable package based on Rollbar, utilizing the latest TS version (currently 4.2.4). Let's delve into some code snipp ...

The ngx-datatable encountered a resolution issue with its dependency tree and was unable to resolve it

I've been trying to incorporate ngx-datatables into an Angular 12 project by running the command npm install @swimlane/ngx-datatable. However, after installation, I encountered the following Errors: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to r ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...