【问题标题】:Configure mailgun in TypeScript for Firebase Cloud Function在 TypeScript 中为 Firebase Cloud Function 配置 mailgun
【发布时间】:2019-07-11 15:09:59
【问题描述】:

我正在 Firebase 中使用 Cloud Functions 发送一封电子邮件,使用 mailgun 在documentation 之后发送电子邮件。

我正在使用 TypeScript,但我找不到有关如何设置 API KEY、DOMAIN 以及最后如何发送电子邮件的示例。我找到的所有示例都在 JavaScript 中。

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 <me@samples.mailgun.org>',
  to: 'foo@example.com, bar@example.com',
  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 ?

我曾尝试使用ts-mailgun,这是一个用于发送电子邮件的包装器,但由于部署该功能时出错而无法正常工作。

我的目标是使用 TypeScript 正确配置 mailgun 以向用户发送电子邮件。

【问题讨论】:

  • 您收到了什么错误,您是否已将计划升级到 Flame 或 Blaze...您需要其中一种付费计划才能向非 Google 服务发出 API 请求?

标签: typescript google-cloud-functions mailgun


【解决方案1】:

npm i ts-mailgun

然后:


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 = 'noreply@my-sample-app.com'; // Set your from email
mailer.fromTitle = 'My Sample App'; // Set the name you would like to send from

mailer.init();

// Send an email to test@example.com
mailer
    .send('test@example.com', 'Hello!', '<h1>hsdf</h1>')
    .then((result) => console.log('Done', result))
    .catch((error) => console.error('Error: ', error));

来自ts-mailgun documentation

【讨论】:

【解决方案2】:

这个问题来自一年多以前,但在检查了@types/mailgun-js 页面中链接的 GitHub 页面后:

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

您可以看到 ConstructorParams 接口,并查看它被调用的位置。看起来您需要实例化mailgun,如下所示。完成此操作后,这些类型开始为我工作。

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);

【讨论】:

    猜你喜欢
    • 2020-07-25
    • 2020-04-02
    • 1970-01-01
    • 2021-04-06
    • 2020-10-26
    • 1970-01-01
    • 2021-04-13
    • 2018-09-09
    • 2022-12-12
    相关资源
    最近更新 更多