javascript - 使用 Loopback 4 发送电子邮件

标签 javascript typescript strongloop loopback loopback4

我对 Loopback 和 Typescript 有点陌生,所以我不知道如何实现它。我试图直接调用 Nodemailer,但到目前为止我一直收到错误消息。

我的邮件服务:

import { SentMessageInfo } from 'nodemailer';
import Mail = require('nodemailer/lib/mailer');
const nodemailer = require("nodemailer");

export class MailerService {
  async sendMail(mailOptions: Mail.Options): Promise<SentMessageInfo> {
    const transporter = nodemailer.createTransport({
      host: 'smtp.ethereal.email',
      port: 587,
      auth: {
        user: 'albert.grimes@ethereal.email',
        pass: 'qN85JT6SneBA9S5dhy'
      }
    });
    return await transporter.sendMail(mailOptions);
  }
}

我的邮件 Controller :

import { Request, RestBindings, get, ResponseObject } from 

'@loopback/rest';
import { inject } from '@loopback/context';
import { MailerService } from "../services";

export class MailController {
  constructor(
    @inject ???
    public mailerService: MailerService
  ) { }

  @get('/mail/acceptation')
  async sendEmail(email: string): Promise<any> {
    let info = await this.mailerService.sendMail({
      to: `${email}`,
      subject: 'testmail',
      html: '<p>Hallo</p>'
    })
    return info;
  }
}

我一直收到这个错误:

Unhandled error in GET /mail/acceptation: 500 Error: Cannot resolve injected arguments for MailController.prototype.sendEmail[0]: The arguments[0] is not decorated for dependency injection, but a value is not supplied

所以我从中收集到的是我应该在我的 Controller 中注入(inject)一个值,但我不知道是什么。

最佳答案

email.service.ts

import Utils from '../utils';
import * as nodemailer from 'nodemailer';
import { IEmail } from '../type-schema';

export interface EmailManager<T = Object> {
  sendMail(mailObj: IEmail): Promise<T>;
}

export class EmailService {
  constructor() { }

  async sendMail(mailObj: IEmail): Promise<object> {
    const configOption = Utils.getSiteOptions();

    let transporter = nodemailer.createTransport(configOption.email);

    return await transporter.sendMail(mailObj);
  }
}

在您的配置文件中定义您的 smtp 选项,如下所示:-

"email": {
    "type": "smtp",
    "host": "smtp.gmail.com",
    "secure": true,
    "port": 465,
    "tls": {
      "rejectUnauthorized": false
    },
    "auth": {
      "user": "example@gmail.com",
      "pass": "sample-password"
    }
  }

在 Controller 中像下面这样发送邮件:-

import { EmailManager } from '../services/email.service';
import { EmailManagerBindings } from '../keys';

// inject in constructor
@inject(EmailManagerBindings.SEND_MAIL) public emailManager: EmailManager,

// call service method like following way
const mailOptions = {
          from: configOption.fromMail,
          to: getUser.email,
          subject: template.subject,
          html: Utils.filterEmailContent(template.message, msgOpt)
        };

        await this.emailManager.sendMail(mailOptions).then(function (res: any) {
          return { message: `Successfully sent reset mail to ${getUser.email}` };
        }).catch(function (err: any) {
          throw new HttpErrors.UnprocessableEntity(`Error in sending E-mail to ${getUser.email}`);
        });

简单方法:- 如果你不想做一个服务功能,只需在你的 Controller 中导入 nodemailer 并发送邮件,但这不是一个好的方法。

import * as nodemailer from 'nodemailer';

let transporter = nodemailer.createTransport({
    "type": "smtp",
    "host": "smtp.gmail.com",
    "secure": true,
    "port": 465,
    "tls": {
      "rejectUnauthorized": false
    },
    "auth": {
      "user": "example@gmail.com",
      "pass": "sample-password"
    }
  });

 return await transporter.sendMail({
          from: "sender-email",
          to: "receiver-email",
          subject: "email-subject",
          html: "message body"
        });

更新:-

keys.ts

import { BindingKey } from '@loopback/context';    
import { EmailManager } from './services/email.service';    
import { Member } from './models';
import { Credentials } from './type-schema';

export namespace PasswordHasherBindings {
  export const PASSWORD_HASHER = BindingKey.create<PasswordHasher>('services.hasher');
  export const ROUNDS = BindingKey.create<number>('services.hasher.round');
}

export namespace UserServiceBindings {
  export const USER_SERVICE = BindingKey.create<UserService<Member, Credentials>>('services.user.service');
}

export namespace TokenManagerBindings {
  export const TOKEN_HANDLER = BindingKey.create<TokenManager>('services.token.handler');
}

export namespace EmailManagerBindings {
  export const SEND_MAIL = BindingKey.create<EmailManager>('services.email.send');
}

应用程序.ts

import { BootMixin } from '@loopback/boot';
import { ApplicationConfig } from '@loopback/core';
import { RepositoryMixin } from '@loopback/repository';
import { RestApplication } from '@loopback/rest';
import { ServiceMixin } from '@loopback/service-proxy';
import * as path from 'path';
import { MySequence } from './sequence';

import { TokenServiceBindings, UserServiceBindings, TokenServiceConstants, } from './keys';
import { JWTService, TokenGenerator } from './services/jwt-service';
import { EmailService } from './services/email.service';
import { MyUserService } from './services/user-service';
import { AuthenticationComponent, registerAuthenticationStrategy, } from '@loopback/authentication';
import { PasswordHasherBindings, TokenManagerBindings, EmailManagerBindings } from './keys';
import { BcryptHasher } from './services/hash.password.bcryptjs';
import { JWTAuthenticationStrategy } from './authentication-strategies/jwt-strategy';

export class AmpleServerApplication extends BootMixin(ServiceMixin(RepositoryMixin(RestApplication))) {
  constructor(options: ApplicationConfig = {}) {
    super(options);

    this.setUpBindings();

    // Bind authentication component related elements
    this.component(AuthenticationComponent);

    registerAuthenticationStrategy(this, JWTAuthenticationStrategy);

    // Set up the custom sequence
    this.sequence(MySequence);

    // Set up default home page
    this.static('/', path.join(__dirname, '../public'));

    this.projectRoot = __dirname;

    this.bootOptions = {
      controllers: {
        dirs: ['controllers'],
        extensions: ['.controller.js'],
        nested: true,
      },
    };
  }

  setUpBindings(): void {
    this.bind(TokenServiceBindings.TOKEN_SECRET).to(TokenServiceConstants.TOKEN_SECRET_VALUE);
    this.bind(TokenServiceBindings.TOKEN_EXPIRES_IN).to(TokenServiceConstants.TOKEN_EXPIRES_IN_VALUE);

    this.bind(UserServiceBindings.USER_SERVICE).toClass(MyUserService);

    this.bind(EmailManagerBindings.SEND_MAIL).toClass(EmailService);
  }
}

关于javascript - 使用 Loopback 4 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57182231/

相关文章:

javascript - 如何在不使用 &lt;iframe&gt; 标签的情况下在 iframe 中加载聊天应用程序?

javascript - Angular/Firestore - 获取由 'add' 方法创建的 ID 以用于路由器导航

javascript - 如何管理状态?

reactjs - React TypeScript onSubmit e.preventDefault() 不起作用

typescript - 为什么我们要为也可以在 src 文件夹中运行测试的编程语言编写一个额外的测试文件夹?

node.js - 从 StrongLoop 中的相关模型返回附加字段

node.js - 我想升级 Node 环回应用程序中的所有 npm 包

javascript函数返回不起作用

angular - 如何将结构化数据转化为可观察数据?

node.js - 以内存为数据源的环回测试