首页 > 解决方案 > 如何在 Nestjs API 中为电子邮件模板提供静态文件

问题描述

我想在公用文件夹中有一个电子邮件模板。我不知道如何使电子邮件模板在发送电子邮件功能中导入/可用。我收到这个错误。

找不到模块'../../public/view/email-template'.t

我已经为嵌套添加了这一行,以使用公共文件夹来提供其中包含 HTML、CSS 和 js 文件的静态文件。

  app.useStaticAssets(join(__dirname, '..', 'public'));

这是发送电子邮件模板功能

import nodemailer = require('nodemailer');
import sgTransport = require('nodemailer-sendgrid-transport');
import {emailTem} from '../../public/view/email-template'; //This is where I am importing the HTML template

export const SendEmail = async (email: string, link: string, name: string) => {

    const options = {
        auth: {
            api_user: process.env.SG_UserName,
            api_key: process.env.SG_Password
        }
    }


    const client = nodemailer.createTransport(sgTransport(options));

    const emailObj = {
        from: 'noreply@mail.com',
        to: email,
        subject: "Email Confirmation from Us",
        text: emailTem,
        html: emailTem
    };

    client.sendMail(emailObj, function (err, info) {
        if (err) {
            console.log(err);
        }
        else {
            console.log('Message sent: ' + link);
        }
    });

}
 }

标签: node.jsangularexpressnestjsemail

解决方案


在您的 email-template.js 中,编写一个将 html 导出为字符串的函数,然后使用它。

export function emailTem() {
let html =`<html></html>`;
return html;
}

在发送电子邮件模板功能中,

import {emailTem} from '../../public/view/email-template';

推荐阅读