电子邮件服务.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"
}
}
在控制器中发送邮件,如下所示:-
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}`);
});
简单方法:-
如果您不想创建服务功能,只需在控制器中导入 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"
});
更新:-
键.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);
}
}