You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导出的Nodemailer sendEmail函数在index.ts中未执行求助

问题:Nodemailer的sendEmail函数调用后无输出,其他代码正常执行

代码示例

sendEmail.ts 文件

import nodemailer from 'nodemailer';
import chalk from 'chalk';

// async..await is not allowed in global scope, must use a wrapper
export async function sendEmail(to: string, text: string) {
    // Generate test SMTP service account from ethereal.email
    // Only needed if you don't have a real mail account for testing
    let testAccount = await nodemailer.createTestAccount();
    // DOES NOT APPEAR IN NODE CONSOLE
    console.log(chalk.red("testaccount", testAccount));
  
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
      host: "smtp.ethereal.email",
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: testAccount.user, // generated ethereal user
        pass: testAccount.pass, // generated ethereal password
      },
    });
  
    // send mail with defined transport object
    let info = await transporter.sendMail({
      from: '"Fred Foo 👻" <foo@example.com>', // sender address
      to: to, // list of receivers
      subject: "Change Password", // Subject line
      text: text, // plain text body
      html: "<b>Hello world?</b>", // html body
    });
  
    console.log("Message sent: %s", info.messageId);
    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}

index.ts 文件

// import the exported function
import { sendEmail } from "./utils/sendEmail";

const main = async () => {
  console.log(chalk.bgRed.bold("TEST TEST")) // <- Prints to console
  sendEmail("testemail@gmail.com", "hello there"); // <- Does not print
  const orm = await MikroORM.init(mikroConfig); // <- Prints
  await orm.getMigrator().up(); 
  const app = express();
  // ...... other config logic ......
};

main().catch((err) => {
  console.log(err);
});

问题原因

sendEmail是异步函数,但调用时未添加await关键字,导致:

  1. main函数不会等待sendEmail执行完成,直接推进后续代码
  2. 如果sendEmail内部出现错误,错误无法被main函数的catch块捕获,既看不到输出也看不到报错信息

解决方案

  1. 添加await关键字:调用sendEmail时加上await,确保函数执行完成后再继续后续逻辑:
await sendEmail("testemail@gmail.com", "hello there");
  1. 补充依赖导入:index.ts中使用了chalk但未导入,需添加:
import chalk from 'chalk';
  1. 排查其他可能问题:
  • 确认nodemailer和chalk依赖已正确安装:执行npm install nodemailer chalk
  • 检查网络连接:nodemailer.createTestAccount()需要联网获取测试账户,网络不通会导致函数卡住或出错

内容的提问来源于stack exchange,提问作者paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:45:22