我正在尝试将 pdf 附件文件从表单直接发送到电子邮件
我在 nextjs 14 服务器端运行 Nodemailer
根据nodemailer文档,content属性可以是任何类型
String
,Buffer
或Stream
。
我尝试了字符串选项,它有效(✅)我坚持了另外 2 个选项(❌)
我尝试了使用 path property 而不是 content property 的另一个选项,它有效(✅),我没有寻找答案,因为我认为如果可以从表单缓冲或流式传输 pdf,这将是比将 pdf 上传到远程存储并获取 URL 路径以将其传递到 path 属性 .
更直接、更轻松将 pdf 转换为缓冲区的最后尝试步骤是:
"use server";
import { mailOptions, transporter } from "../config/nodemailer";
interface EmailInputes {
name: string;
file: File | null;
}
export async function submittingEmail({ name, file }: EmailInputes) {
if (!file) return;
// --- her I'm trying to converting file to buffer ---
const arrayBuffer = await file.arrayBuffer();
const fileBuffer = Buffer.from(arrayBuffer);👈
await transporter.sendMail({
...mailOptions,
attachments: [
{
filename: "test.pdf",
content: fileBuffer,👈
},
],
subject: `Testing Attachments`,
text: "this a text",
html: `
<!DOCTYPE html>
<html>
<body style="direction:rtl">
<h1 style="color:darkgreen; text-align: center;margin:0;font-size:24px">Testing Attachments</h1>
<p>contact visitor name is : ${name}</p>
</body>
</html>
`,
});
}
当我以这种方式提交时,我收到错误并且没有发送任何内容
要使用 Next.js 中的 nodemailer 将 PDF 文件作为缓冲区或流发送,而不将其上传到远程存储,您可以将文件从表单输入转换为缓冲区,然后将其附加到您的电子邮件。您可以按照以下步骤一步步完成此操作。
您已经从表单输入中获得了文件。您需要将此文件转换为缓冲区并将其发送到您的 Next.js API 路由。
以下是如何在将文件发送到 API 之前在前端处理文件的示例:
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
const fileInput = event.target.elements.file; // Assuming your input name is 'file'
formData.append('file', fileInput.files[0]);
const response = await fetch('/api/send-email', {
method: 'POST',
body: formData,
});
if (response.ok) {
console.log('Email sent successfully');
} else {
console.error('Error sending email');
}
};
接下来,您将在 Next.js 中创建一个 API 路由,用于处理传入的表单数据、将文件转换为缓冲区,并使用 Nodemailer 发送它。
import { NextRequest, NextResponse } from 'next/server';
import formidable from 'formidable';
import fs from 'fs';
import nodemailer from 'nodemailer';
// Disable body parsing for this route
export const config = {
api: {
bodyParser: false,
},
};
export async function POST(req, res) {
// Parse incoming form data
const form = new formidable.IncomingForm();
form.uploadDir = './temp'; // Temporary directory to store uploaded files
form.parse(req, async (err, fields, files) => {
if (err) {
return NextResponse.json({ error: 'Error parsing the file' }, { status: 500 });
}
// Access the uploaded file
const file = files.file[0]; // Assuming only one file is uploaded
// Read the file as a buffer
const fileBuffer = fs.readFileSync(file.filepath);
// Nodemailer setup
const transporter = nodemailer.createTransport({
service: 'your_email_service', // e.g., 'gmail'
auth: {
user: '[email protected]',
pass: 'your_email_password',
},
});
// Email options
const mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Here is your PDF',
text: 'Please find the attached PDF.',
attachments: [
{
filename: file.originalFilename,
content: fileBuffer, // Use the buffer here
contentType: 'application/pdf',
},
],
};
// Send the email
try {
await transporter.sendMail(mailOptions);
return NextResponse.json({ message: 'Email sent successfully' }, { status: 200 });
} catch (error) {
console.error('Error sending email:', error);
return NextResponse.json({ error: 'Error sending email' }, { status: 500 });
}
});
}
fs.readFileSync(file.filepath)
将上传的文件转换为缓冲区。mailOptions
中,使用 content
属性和您创建的缓冲区附加文件。要使用
formidable
和nodemailer
,您需要安装它们:
npm install formidable nodemailer
"your_email_service"
、"[email protected]"
和 "your_email_password"
替换为实际值。此设置应该允许您直接从表单处理 PDF 附件作为缓冲区,使流程更加简化和高效!