nuxt服务器中的Express Nodemailer中间件-错误:生成/ usr / sbin / sendmail ENOENT

时间:2019-03-16 10:00:56

标签: express sendmail nodemailer nuxt

我正在尝试在基于NuxtJs的静态站点中发送简单的POST请求联系表格。

我正在尝试使用express Nuxt提供的nodemailerserverMiddleware

这是api/contact.js

中的代码
const express = require('express')
const nodemailer = require('nodemailer')
const validator = require('validator')
const xssFilters = require('xss-filters')

const app = express()
app.use(express.json())

const rejectFunctions = new Map([
  ['name', a => a.trim().length < 4],
  ['email', v => !validator.isEmail(v)],
  ['message', v => v.trim().length < 10]
])

const validateAndSanitize = (key, value) => {
  return (
    rejectFunctions.has(key) &&
    !rejectFunctions.get(key)(value) &&
    xssFilters.inHTMLData(value)
  )
}

const sendMail = (name, email, msg) => {
  const transporter = nodemailer.createTransport({
    sendmail: true,
    newline: 'unix',
    path: '/usr/sbin/sendmail'
  })
  transporter.sendMail(
    {
      from: email,
      to: 'johndoe@mail.com',
      subject: 'New Contact Form',
      text: msg
    }
  )
}

app.post('/', (req, res) => {

  const attributes = ['name', 'email', 'message']
  const sanitizedAttributes = attributes.map(attr =>
    validateAndSanitize(attr, req.body[attr])
  )

  const someInvalid = sanitizedAttributes.some(r => !r)

  if (someInvalid) {
    return res
      .status(422)
      .json({ error: 'Error : at least one fiel is invalid' })
  }

  sendMail(...sanitizedAttributes)

  res.status(200).json({ message: 'OH YEAH' })
})

export default {
  path: '/api/contact',
  handler: app
}

一切正常,直到sendMail函数出现此错误为止:

(node:10266) UnhandledPromiseRejectionWarning: Error: spawn /usr/sbin/sendmail ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:19)
    at onErrorNT (internal/child_process.js:427:16)
    at processTicksAndRejections (internal/process/next_tick.js:76:17)
(node:10266) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)

知道我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

错误

Error: spawn /usr/sbin/sendmail ENOENT

表明 nodemailer 在 sendmail 中寻找 /usr/sbin/ 但没有找到(这是默认位置,可以在 pathcreateTransport 选项中配置) )。首先,通过运行确保它不存在(就像 AnFi 建议的那样)

ls -l /usr/sbin/sendmail

如果你得到

ls: cannot access '/usr/bin/sendmail': No such file or directory

然后通过运行安装 sendmail

sudo apt-get install sendmail

然后,尝试 ls -l /usr/sbin/sendmail 并再次发送电子邮件。