Reactjs NodeEmailer不使用手机>&燃气轮机;(使用下一个js api的下一个js web和节点邮箱)
我做了一个简单的网站与联系方式。该网站由Next10、react 17和NodeEmailer创建。联系人表单在笔记本电脑(chrome、firefox)上运行良好,但在移动电话上不起作用。通过联系人表单发送的邮件不会发送到Gmail收件箱。这是代码。 反应钩形式也被使用Reactjs NodeEmailer不使用手机>&燃气轮机;(使用下一个js api的下一个js web和节点邮箱),reactjs,next.js,nodemailer,Reactjs,Next.js,Nodemailer,我做了一个简单的网站与联系方式。该网站由Next10、react 17和NodeEmailer创建。联系人表单在笔记本电脑(chrome、firefox)上运行良好,但在移动电话上不起作用。通过联系人表单发送的邮件不会发送到Gmail收件箱。这是代码。 反应钩形式也被使用 // contactform.js import { useForm } from 'react-hook-form'; import { toast } from 'react-toastify'; import { use
// contactform.js
import { useForm } from 'react-hook-form';
import { toast } from 'react-toastify';
import { useState } from 'react';
import Loader from "react-loader-spinner";
export default function ContactForm() {
const [isLoading, setIsLoading] = useState(false);
const { register, handleSubmit, errors, reset } = useForm();
const onSubmitForm = async (values) => {
let config = {
method: "POST",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify(values)
};
let data;
try {
setIsLoading(true);
const res = await fetch("/api/contact", config);
data = await res.json();
if (data.success === "ok") {
reset();
setIsLoading(false);
return toast.success(data.message, {
position: toast.POSITION.TOP_CENTER
});
}
if (data.success === "fail") {
reset();
setIsLoading(false);
return toast.warn(data.error, {
position: toast.POSITION.TOP_CENTER
});
}
} catch (err) {
reset();
return toast.error(data.error, {
position: toast.POSITION.TOP_CENTER
});
}
};
return (
<div className="relative flex flex-wrap justify-center lg:-mt-64 -mt-48">
<div className="w-full lg:w-6/12 px-4">
<div className="relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded-lg bg-gray-300">
<form
className="flex-auto p-5 lg:p-10"
onSubmit={handleSubmit(onSubmitForm)}
>
<h4 className="text-2xl font-semibold">
Start Your Story
<span className="block sm:inline-block ml-1">
With Us
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="w-4 h-4 mb-3 ml-2 inline rounded-ful text-yellow-500 animate-ping font-bold">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
</svg>
</span>
</h4>
<p className="leading-relaxed mt-1 mb-4 text-gray-600">
무엇이든 물어보세요!
</p>
<p className="leading-relaxed -mt-3 mb-4 text-gray-600">
24시간 안에 답장을 해드리겠습니다.
</p>
<div className="relative w-full mb-3 mt-8">
<label
className="block uppercase text-gray-700 text-xs font-bold mb-2"
htmlFor="full-name"
>
이름
</label>
<input
type="text"
name="name"
ref={register({
required: {
value: true,
message: '이름을 입력 하셔여 합니다!'
}
})}
className={`px-3 py-3 placeholder-gray-400 text-gray-700 bg-white rounded text-sm shadow focus:outline-none focus:shadow-outline w-full ${errors.name ? 'ring-2 ring-red-500': null}`}
placeholder="Full Name"
style={{ transition: "all .15s ease" }}
/>
<span className="text-red-400 text-sm py-2">
{errors?.name?.message}
</span>
</div>
<div className="relative w-full mb-3">
<label
className="block uppercase text-gray-700 text-xs font-bold mb-2"
htmlFor="email"
>
이메일
</label>
<input
type="text"
name="email"
ref={register({
required: {
value: true,
message: '이메일 주소를 입력 하셔여 합니다!'
},
minLength: {
value: 8,
message: '정확한 이메일 주소를 입력 바랍니다!'
},
maxLength: {
value: 30,
message: '정확한 이메일 주소를 입력 바랍니다!'
},
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: "이메일 형식이 틀립니다. 다시 입력 해주세요! "
}
})}
className={`px-3 py-3 placeholder-gray-400 text-gray-700 bg-white rounded text-sm shadow focus:outline-none focus:shadow-outline w-full ${errors.email ? 'ring-2 ring-red-500': null}`}
placeholder="Email"
style={{ transition: "all .15s ease" }}
/>
<span className="text-red-400 text-sm py-2">
{errors?.email?.message}
</span>
</div>
<div className="relative w-full mb-3">
<label
className="block uppercase text-gray-700 text-xs font-bold mb-2"
htmlFor="message"
>
메시지
</label>
<textarea
rows={4}
cols={80}
name="message"
ref={register({
required: {
value: true,
message: '메세지를 입력 하셔여 합니다!'
},
minLength: {
value: 20,
message: '메세지는 20자 이상이여야 합니다!'
},
})}
className={`px-3 py-3 placeholder-gray-400 text-gray-700 bg-white rounded text-sm shadow focus:outline-none focus:shadow-outline w-full ${errors.message ? 'ring-2 ring-red-500': null}`}
placeholder="Type a message..."
/>
<span className="text-red-400 text-sm py-2">
{errors?.message?.message}
</span>
</div>
<div className="text-center mt-6">
<button
className="bg-gray-900 text-white active:bg-gray-700 text-sm font-bold uppercase px-8 py-3 rounded shadow-lg hover:shadow-lg outline-none focus:outline-none mr-1 mb-1 transition duration-300"
type="submit"
>
<span>{isLoading ? ( <Loader
type="TailSpin"
color="#00BFFF"
height={15}
width={15}
timeout={3000}
className="inline-block mr-3"
/>) : null}</span>
보내기
</button>
</div>
</form>
</div>
</div>
</div>
);
}
/api/contact.js
import nodemailer from 'nodemailer';
import Cors from 'cors';
require('dotenv').config();
const cors = Cors({
methods: ['POST'],
origin: 'https://www.veritas101.com',
optionsSuccessStatus: 200
});
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
export default async function handler(req, res) {
await runMiddleware(req, res, cors);
if (!req.body) {
return res.status(400).end();
}
const { name, email, message } = req.body;
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: process.env.NEXT_PUBLIC_USER_EMAIL,
pass: process.env.NEXT_PUBLIC_USER_PASS
}
});
const mailData = {
from: email,
to: process.env.NEXT_PUBLIC_USER_EMAIL,
subject: `Contact form submission from ${name}`,
html: `<h3>You have a new contact from submission</h3><br/>
<h4><strong>Name: </strong>${name}</h4><br/>
<h4><strong>Email: </strong>${email}</h4><br/>
<h4><strong>Message:<br/> </strong>${message}</h4><br/>
`
};
transporter.verify((error, _)=> {
console.error(error);
});
const emailSending = await transporter.sendMail(mailData);
if (!emailSending.messageId) {
return res.status(400).json({ error: "problem" , success: "fail" });
} else {
return res.status(200).json({ message: "success", success: "ok" });
}
}
//contactform.js
从“react hook form”导入{useForm};
从'react toastify'导入{toast};
从“react”导入{useState};
从“react Loader spinner”导入装载机;
导出默认函数ContactForm(){
const[isLoading,setIsLoading]=useState(false);
常量{register,handleSubmit,errors,reset}=useForm();
const onSubmitForm=async(值)=>{
让配置={
方法:“张贴”,
标题:{
“接受”:“application/json,text/plain,*/*”,
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify(值)
};
让数据;
试一试{
设置加载(真);
const res=wait fetch(“/api/contact”,config);
data=wait res.json();
如果(data.success==“ok”){
重置();
设置加载(假);
返回toast.success(data.message{
位置:toast.position.TOP\u居中
});
}
如果(data.success==“fail”){
重置();
设置加载(假);
返回toast.warn(data.error{
位置:toast.position.TOP\u居中
});
}
}捕捉(错误){
重置();
返回toast.error(data.error{
位置:toast.position.TOP\u居中
});
}
};
返回(
开始你的故事
和我们一起
무엇이든 물어보세요!
24시간 안에 답장을 해드리겠습니다.
이름
{错误?.name?.message}
이메일
{错误?.email?.message}
메시지
{错误?.message?.message}
{isLoading?():null}
보내기
);
}
/api/contact.js
从“nodeEmailer”导入nodeEmailer;
从“Cors”进口Cors;
require('dotenv').config();
常数cors=cors({
方法:['POST'],
来源:'https://www.veritas101.com',
选项成功状态:200
});
函数运行中间件(req、res、fn){
返回新承诺((解决、拒绝)=>{
fn(请求、结果)=>{
如果(错误的结果实例){
返回拒绝(结果)
}
返回解析(结果)
})
})
}
导出默认异步函数处理程序(req、res){
等待运行中间件(req、res、cors);
如果(!请求正文){
返回res.status(400.end();
}
const{name,email,message}=req.body;
const transporter=nodemailer.createTransport({
主机:“smtp.gmail.com”,
港口:465,
安全:是的,
认证:{
用户:process.env.NEXT\u PUBLIC\u user\u EMAIL,
通过:process.env.NEXT\u PUBLIC\u USER\u通过
}
});
常量mailData={
发件人:电子邮件,
收件人:process.env.NEXT\u PUBLIC\u USER\u EMAIL,
主题:`Contact form submission from${name}`,
html:`您有一个来自提交的新联系人
名称:${Name}
电子邮件:${Email}
消息:
${Message}
`
};
transporter.verify((错误,41;)=>{
控制台错误(error);
});
const emailSending=wait transporter.sendMail(mailData);
如果(!emailSending.messageId){
返回res.status(400).json({error:“problem”,success:“fail”});
}否则{
返回res.status(200).json({message:“success”,success:“ok”});
}
}