Mailgun-401 forbindden

问题描述

我尝试使用mailgun发送电子邮件。我使用node.js(nest.js),这是我的邮件服务。我应该改变什么?当我尝试发送第一封电子邮件(在mailgun官方网站中进行说明)时,我收到了相同的错误消息。

import { Injectable } from '@nestjs/common';
import * as Mailgun from 'mailgun-js';
import { IMailGunData } from './interfaces/mail.interface';
import { ConfigService } from '../config/config.service';

@Injectable()
export class MailService {
  private mg: Mailgun.Mailgun;

  constructor(private readonly configService: ConfigService) {
    this.mg = Mailgun({
      apiKey: this.configService.get('MAILGUN_API_KEY'),domain: this.configService.get('MAILGUN_API_DOMAIN'),});
  }

  send(data: IMailGunData): Promise<Mailgun.messages.SendResponse> {
    console.log(data);
    console.log(this.mg);
    return new Promise((res,rej) => {
      this.mg.messages().send(data,function (error,body) {
        if (error) {
          console.log(error);
          rej(error);
        }
        res(body);
      });
    });
  }
}

当我尝试发送消息时,出现禁止描述的401错误

我的毫克(console.log(this.mg))

Mailgun {
  username: 'api',apiKey: '920d6161ca860e7b84d9de75e14exxx-xxx-xxx',publicApiKey: undefined,domain: 'lokalne-dobrodziejstwa.pl',auth: 'api:920d6161ca860e7b84d9de75e14exxx-xxx-xxx',mute: false,timeout: undefined,host: 'api.mailgun.net',endpoint: '/v3',protocol: 'https:',port: 443,retry: 1,testMode: undefined,testModeLogger: undefined,options: {
    host: 'api.mailgun.net',proxy: undefined,testModeLogger: undefined
  },mailgunTokens: {}
}

我的电子邮件正文

{
  from: 'rejestracja@lokalne-dobrodziejstwa.pl',to: '[email protected]',subject: 'Verify User',html: '\n' +
    '                <h3>Hello [email protected]!</h3>\n' +
    '            '
}

解决方法

当我的域名位于欧盟区域时,我遇到了这个问题。使用EU区域时,必须在配置中指定它-Mailgun对此没有明确说明。

所以会是这样:

var mailgun = require("mailgun-js")({
  apiKey: API_KEY,domain: DOMAIN,host: "api.eu.mailgun.net",});
,

尝试通过控制台中的以下命令向自己发送电子邮件(帐户电子邮件):

curl -s --user 'api:YOUR_API_KEY' \
    https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages \
    -F from='Excited User <mailgun@YOUR_DOMAIN_NAME>' \
    -F to=YOU@YOUR_DOMAIN_NAME \
    -F [email protected] \
    -F subject='Hello' \
    -F text='Testing some Mailgun awesomeness!'

工作正常吗?

如果不是。 我认为您已经正确地编写了api和域,因此以后如果您有免费帐户,则应在“概述”部分中检查授权收件人(您无法在试用帐户中向任何地方发送电子邮件,必须先输入它)

enter image description here 如果您没有找到解决方案,这就是我完成mailService(工作)的方式,那么您可以尝试一下,我使用nodemailer来做到这一点:

import { Injectable,InternalServerErrorException,OnModuleInit } from '@nestjs/common';
import { readFileSync } from 'fs';
import { compile } from 'handlebars';
import { join } from 'path';
import * as nodemailer from 'nodemailer';
import { Options } from 'nodemailer/lib/mailer';
import * as mg from 'nodemailer-mailgun-transport';

import { IReplacement } from './replacements/replacement';
import { ResetPasswordReplacement } from './replacements/reset-password.replacement';

@Injectable()
export class MailService implements OnModuleInit {
  private transporter: nodemailer.Transporter;

  onModuleInit(): void {
    this.transporter = this.getMailConfig(); 
  }

  sendResetPasswordMail(email: string,firstName: string = '',lastName: string = ''): void { // this is just example method with template but you can use sendmail directly from sendMail method
    const resetPasswordReplacement = new ResetPasswordReplacement({
      firstName,lastName,email,});

    this.sendMail(
      proccess.env.MailBoxAddress),'Change password',this.createTemplate('reset-password',resetPasswordReplacement),);
  }

  sendMail(from: string,to: string,subject: string,body: string): void {
    const mailOptions: Options = { from,to,subject,html: body };

    return this.transporter.sendMail(mailOptions,(error) => {
      if (error) {
        throw new InternalServerErrorException('Error');
      }
    });
  }

  private getMailConfig(): any {
    return nodemailer.createTransport(mg({
      auth: {
        api_key: proccess.env.MailApiKey,domain: proccess.env.MailDomain
      },}));
  }

  private createTemplate(fileName: string,replacements: IReplacement): string {
    const templateFile = readFileSync(join(__dirname,'templates',`${fileName}.html`),{ encoding: 'utf-8' });
    const template = compile(templateFile);
    return template(replacements);
  }
}

const templateFile = readFileSync(join(__dirname,{ encoding: 'utf-8' });

定义包含内容的html文件的位置,以使其外观(在本例中为reset-password.html):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Password reset</title>
</head>
<body>
  <div>Welcome {{firstName}} {{lastName}}</div>
</body>
</html>

{{}}中的值将被库自动替换

在此示例示例 ResetPasswordReplacement 中,它仅包含3个属性的基本对象,并由IReplacement继承,该接口为空接口-仅用于定义模板文件中的值

来源:

  1. https://www.npmjs.com/package/nodemailer-mailgun-transport
  2. https://documentation.mailgun.com/en/latest/quickstart-sending.html#send-with-smtp-or-api
,

另一个可能发生在我身上的案例:
我最初使用 npm 安装了 mailgun-js 并开始使用 yarn,然后它在每个请求中返回 401 Forbidden。所以yarn add mailgun-js解决了它。