我正在尝试使用 nodemailer 在我的 Next.js 应用程序中发送文件附件。
我当前的设置包括:
ApplicationForm.tsx
import { sendEmailForm } from '../../../../lib/api';
const initialState: IApplicationFormData = {
files: [],
};
const ApplicationForm = () => {
const [formData, setFormData] = useState<IApplicationFormData>(initialState);
const handleFileUpload = (
e: React.ChangeEvent<HTMLInputElement> | React.DragEvent<HTMLDivElement>
) => {
e.preventDefault();
let fileList;
if (e.type === 'change') {
fileList = (e.target as HTMLInputElement).files;
} else {
fileList = (e as React.DragEvent<HTMLDivElement>).dataTransfer.files;
}
const fileArray = Array.from(fileList || []);
setFormData((current) => ({
...current,
files: [...current.files, ...fileArray],
}));
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
try {
await sendEmailForm(formData, 'applicationMail');
setFormData(initialState);
} catch (error: any) {
console.log(error.message)
});
}
};
return(
<FileInput
name={fileLabel}
labelText={fileLabel}
onChange={handleFileUpload}
filePreview={formData.files}
removeFile={removeFile}
removeAllFiles={removeAllFiles}
handleDragOver={handleDragOver}
/>
)
export default ApplicationForm;
我将state中上传的文件保存为数组。
遵循
lib/api.ts
中的fetch函数
export const sendEmailForm = async (
data: any,
apiEndpoint: 'applicationMail' | 'contactMail' | 'callbackMail'
) => {
fetch(`/api/${apiEndpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(data),
}).then((res) => {
if (!res.ok)
throw new Error(`Failed to send email, status code: ${res.status}`);
return res.json();
});
};
Next.js API
applicationMail.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import {
applicationEmailTransporter,
applicationMailOptions,
} from '../../services/nodemailer';
import { generateEmailTemplate } from './../../lib/emailTemplate';
const applicationFormHandler = async (
req: NextApiRequest,
res: NextApiResponse
) => {
const data = req.body;
if (req.method === 'POST') {
if (!data.firstName || !data.lastName || !data.email || !data.message)
return res.status(400).json({ message: 'Bad request' });
}
try {
await applicationEmailTransporter.sendMail({
...applicationMailOptions,
...generateEmailTemplate(data),
subject: 'New message',
});
if (data.email && data.email.length > 0) {
try {
await applicationEmailTransporter.sendMail({
to: data.email,
from: process.env.NEXT_PUBLIC_APPLICATION_EMAIL,
subject: 'subject',
text: `text`,
html: `<p>html</p>`,
});
} catch (error) {
console.log(error.message)
}
}
return res.status(200).json({ message: 'Success' });
} catch (error: any) {
return res.status(400).json({ message: error.message });
}
};
export default applicationFormHandler;
最后是运输机的
nodemailer.js
import nodemailer from 'nodemailer';
const applicationEmail = process.env.NEXT_PUBLIC_APPLICATION_EMAIL;
const applicationEmailPassword =
process.env.NEXT_PUBLIC_APPLICATION_EMAIL_PASSWORD;
export const applicationEmailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: applicationEmail,
pass: applicationEmailPassword,
},
});
export const applicationMailOptions = {
from: applicationEmail,
to: applicationEmail,
attachments: [
{
// Retrieve formData.files data from ApplicationForm.tsx
// filename: 'test.png',
// path: './public/assets/test.png',
},
],
};
我的问题是是否可以仅使用nodemailer发送包含来自我的
ApplicationForm.tsx
的文件数据的附件,或者我是否需要像multer
这样的包?
我如何重构当前的设置以正确发送上传的文件。
提前致谢!
我遇到了类似的问题。有更新吗?