Javascript 使用回送4发送电子邮件
我对环回和打字脚本有点陌生,所以我不知道如何实现它。我试图直接给NodeEmailer打电话,但到目前为止我一直收到一个错误 我的邮件服务:Javascript 使用回送4发送电子邮件,javascript,typescript,strongloop,loopback,loopback4,Javascript,Typescript,Strongloop,Loopback,Loopback4,我对环回和打字脚本有点陌生,所以我不知道如何实现它。我试图直接给NodeEmailer打电话,但到目前为止我一直收到一个错误 我的邮件服务: import { SentMessageInfo } from 'nodemailer'; import Mail = require('nodemailer/lib/mailer'); const nodemailer = require("nodemailer"); export class MailerService { async sendM
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);
}
}
从'nodeEmailer'导入{SentMessageInfo};
导入邮件=require('nodemailer/lib/mailer');
const nodemailer=require(“nodemailer”);
导出类邮件服务{
异步sendMail(mailpoptions:Mail.Options):承诺{
const transporter=nodemailer.createTransport({
主机:“smtp.ethereal.email”,
港口:587,
认证:{
用户:“阿尔伯特。grimes@ethereal.email',
通行证:“qN85JT6SneBA9S5dhy”
}
});
返回等待transporter.sendMail(邮件选项);
}
}
我的邮件控制器:
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;
}
}
import{Request,RestBindings,get,ResponseObject}from
“@loopback/rest”;
从'@loopback/context'导入{inject};
从“./services”导入{MailerService};
导出类邮件控制器{
建造师(
@注射???
公共邮件服务:邮件服务
) { }
@获取(“/mail/acception”)
异步发送电子邮件(电子邮件:字符串):承诺{
let info=等待this.mailerService.sendMail({
收件人:`${email}`,
主题:“testmail”,
html:“你好”
})
退货信息;
}
}
我一直认为这是一个错误:
GET/mail/Acception中未处理的错误:500错误:无法解析MailController.prototype.sendEmail[0]的注入参数:参数[0]未修饰为依赖项注入,但未提供值
所以我从中得到的是,我应该在我的控制器中注入一个值,但我不知道是什么 您应该有一个存储您的文件。您必须在此处创建绑定密钥:
export namespace MailerBindings {
export const SERVICE = BindingKey.create<MailerService>('mailer.services');
}
现在,您可以使用绑定注入服务:
@inject(MailerBindings.SERVICE) public mailerService: MailerService,
有一个关于这个的教程。它有一个特殊的邮件连接器,可以用作数据源。模型应该能够处理发送细节。该过程应与使用lb4 cli创建db连接器时的过程基本相同 cli
lb4 datasource //select email
datasources.json
{
...
"myEmailDataSource": {
"connector": "mail",
"transports": [{
"type": "smtp",
"host": "smtp.private.com",
"secure": false,
"port": 587,
"tls": {
"rejectUnauthorized": false
},
"auth": {
"user": "me@private.com",
"pass": "password"
}
}]
}
...
}
模型
module.exports=函数(MyModel){
//发送电子邮件
MyModel.sendEmail=函数(cb){
MyModel.app.models.Email.send({
致:'foo@bar.com',
发件人:'you@gmail.com',
主题:“我的主题”,
文本:“我的文本”,
html:“我的html”
},函数(错误,邮件){
log('email sent!');
cb(err);
});
}
};`
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);
}
}
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');
}
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);
}
}
在控制器中,按以下方式发送邮件:-
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}`);
});
简单方法:-
如果您不想实现服务功能,只需在控制器中导入NodeEmailer并发送邮件,但这不是一个好方法
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 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);
}
}
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');
}
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);
}
}
我现在更糊涂了。我不明白为什么发送电子邮件要这么复杂。不过还是要谢谢你。这看起来很复杂,因为它是作为服务实现的。您可以像下面的链接中列出的那样使用它,但是您必须在应用程序中发送邮件的每个部分都实现它。通过将其实现为服务,您可以在应用程序的多个部分更轻松地使用它。链接:很抱歉,回复晚了。您能告诉我如何将您的服务绑定到应用程序吗?这是我遇到的最后一个问题。@Peterrosevelt我已经更新了我的答案,以显示“如何在我的用户控制器文件中绑定电子邮件服务?”有关于环回4的文档吗?