前置动作
从QQ邮箱中,获取授权码,具体方式请自行百度
代码撰写
环境安装
npm install nodemailer
创建一个用于发送邮件的Service
import {injectable, /* inject, */ BindingScope} from '@loopback/core';
import nodemailer from 'nodemailer';
@injectable({scope: BindingScope.TRANSIENT})
export class MailService {
private transporter: nodemailer.Transporter;
constructor() {
this.transporter = nodemailer.createTransport({
host: 'smtp.qq.com', //QQ邮箱的服务器
port: 465, //SMTP地址,从邮件服务提供商获取
secure: true, //465端口为true,其他接口为false
auth: {
user: '', // 自己的邮箱
pass: '', // 邮箱授权码,从邮件服务提供商获取
},
});
}
async sendEmail(to: string, subject: string, text: string) {
// 创建邮件选项对象
const mailOptions: nodemailer.SendMailOptions = {
from: '', // 替换为你的 QQ 邮箱地址
to,
subject,
text,
};
// 使用 SMTP 运输器发送邮件
await this.transporter.sendMail(mailOptions);
}
}
在控制器中注入依赖,并调用sendMail方法
import {service} from '@loopback/core';
import {get} from '@loopback/rest';
import {MailService} from '../services';
export class EmailController {
@service(MailService) emailService: MailService;
async sendEmail() {
const to = ''; // 替换为收件人的邮箱地址
const subject = 'Hello';
const text = 'This is a test email';
// 调用邮件服务发送邮件
await this.emailService.sendEmail(to, subject, text);
return 'Email sent successfully';
}
@get('/send-mail')
async callsendMail() {
await this.sendEmail();
}
}
验收
- 点击执行
- 查看收到的邮件