import sendgrid from "@sendgrid/mail";
sendgrid.setApiKey(
"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"
);
async function sendEmail(req, res) {
try {
await sendgrid.send({
to: "umairtextie3@gmail.com", // Your email where you'll receive emails
from: "example@email.com", // your website email address here
subject: `[Lead from website] : ${req.body.subject}`,
html: `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<div class="img-container" style="display: flex;justify-content: center;align-items: center;border-radius: 5px;overflow: hidden; font-family: 'helvetica', 'ui-sans';">
</div>
<div class="container" style="margin-left: 20px;margin-right: 20px;">
<h3>You've got a new mail from ${req.body.fullname}, their email is: ✉️ ${req.body.email} </h3>
<div style="font-size: 16px;">
<p>Message:</p>
<p>${req.body.message}</p>
<br>
</div>
<p class="footer" style="font-size: 16px;padding-bottom: 20px;border-bottom: 1px solid #D1D5DB;">Regards<br>Umair Amir<br>Software Developer<br>+92 3168946190</p>
<div class="footer-links" style="display: flex;justify-content: center;align-items: center;">
<a href="https://manuarora.in/" style="text-decoration: none;margin: 8px;color: #9CA3AF;">Website</a>
<a href="https://manuarora.in/blog/" style="text-decoration: none;margin: 8px;color: #9CA3AF;">Blog</a>
<a href="https://github.com/manuarora700/" style="text-decoration: none;margin: 8px;color: #9CA3AF;">GitHub</a>
<a href="https://instagram.com/maninthere/" style="text-decoration: none;margin: 8px;color: #9CA3AF;">Instagram</a>
<a href="https://linkedin.com/in/manuarora28/" style="text-decoration: none;margin: 8px;color: #9CA3AF;">LinkedIn</a>
<a href="https://twitter.com/mannupaaji/" style="text-decoration: none;margin: 8px;color: #9CA3AF;">Twitter</a>
</div>
</div>
</body>
</html>`,
});
} catch (error) {
// console.log(error);
return res.status(error.statusCode || 500).json({ error: error.message });
}
return res.status(200).json({ error: "" });
}
export default sendEmail;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
above code is my sendgrid component. This component is for send all contact form's field data to my email. {to: "here is the email which I want to receive user data"} .
Below code is my Contact form and in this component check this line code error and solve it if you can.
const res = await fetch("/sendgrid", {
body: JSON.stringify({
email,
fullname,
subject,
message,
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const { error } = await res.json();
if (error) {
console.log(error);
setShowSuccessMessage(false);
setShowFailureMessage(true);
setButtonText("Send");
return;
}
setShowSuccessMessage(true);
setShowFailureMessage(false);
setButtonText("Send");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React, { useState } from "react";
import {
Box,
Button,
CardContent,
Container,
Grid,
Paper,
TextField,
Typography,
} from "@mui/material";
const Contact = () => {
// States for contact form fields
const [fullname, setFullname] = useState("");
const [email, setEmail] = useState("");
const [subject, setSubject] = useState("");
const [message, setMessage] = useState("");
// Form validation state
const [errors, setErrors] = useState({});
// Setting button text on form submission
const [buttonText, setButtonText] = useState("Send");
// Setting success or failure messages states
const [showSuccessMessage, setShowSuccessMessage] = useState(false);
const [showFailureMessage, setShowFailureMessage] = useState(false);
// Validation check method
const handleValidation = () => {
let tempErrors = {};
let isValid = true;
if (fullname.length <= 0) {
tempErrors["fullname"] = true;
isValid = false;
}
if (email.length <= 0) {
tempErrors["email"] = true;
isValid = false;
}
if (subject.length <= 0) {
tempErrors["subject"] = true;
isValid = false;
}
if (message.length <= 0) {
tempErrors["message"] = true;
isValid = false;
}
setErrors({ ...tempErrors });
console.log("errors", errors);
return isValid;
};
// Handling form submit
const handleSubmit = async (e) => {
e.preventDefault();
let isValidForm = handleValidation();
if (isValidForm) {
setButtonText("Sending");
const res = await fetch("/sendgrid", {
body: JSON.stringify({
email,
fullname,
subject,
message,
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const { error } = await res.json();
if (error) {
console.log(error);
setShowSuccessMessage(false);
setShowFailureMessage(true);
setButtonText("Send");
return;
}
setShowSuccessMessage(true);
setShowFailureMessage(false);
setButtonText("Send");
}
console.log(fullname, email, subject, message);
};
return (
<>
<Container>
<Box mb={10}>
<Typography
variant="h3"
textAlign="center"
p={2}
mb={2}
fontSize="3rem"
>
Contact Form
</Typography>
<Paper
elevation={24}
style={{
maxWidth: "40rem",
alignItems: "center",
justifyContent: "center",
margin: "0 auto",
}}
>
<form onSubmit={handleSubmit}>
<CardContent>
<Grid container spacing={1}>
<Grid item xs={12}>
<TextField
label="Full Name"
type="text"
name="fullname"
value={fullname}
onChange={(e) => {
setFullname(e.target.value);
}}
placeholder="Enter Your Name"
variant="outlined"
fullWidth
required
>
{errors?.fullname && (
<p style={{ color: "red" }}>
Fullname cannot be empty.
</p>
)}
</TextField>
</Grid>
</Grid>
</CardContent>
<CardContent>
<Grid container spacing={1}>
<Grid item xs={12}>
<TextField
label="Email"
type="email"
name="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
placeholder="Enter Your Email"
variant="outlined"
fullWidth
required
>
{errors?.email && (
<p style={{ color: "red" }}>
Email field cannot be empty.
</p>
)}
</TextField>
</Grid>
</Grid>
</CardContent>
<CardContent>
<Grid container spacing={1}>
<Grid item xs={12}>
<TextField
label="Subject"
type="text"
name="subject"
value={subject}
onChange={(e) => {
setSubject(e.target.value);
}}
placeholder="What is Subject"
variant="outlined"
fullWidth
required
>
{errors?.subject && (
<p style={{ color: "red" }}>
Subject field cannot be empty.
</p>
)}
</TextField>
</Grid>
</Grid>
</CardContent>
<CardContent>
<Grid container spacing={1}>
<Grid item xs={12}>
<TextField
label="Message"
value={message}
onChange={(e) => {
setMessage(e.target.value);
}}
placeholder="Type your message here"
variant="outlined"
rows={5}
fullWidth
required
multiline
>
{errors?.message && (
<p style={{ color: "red" }}>
Message field cannot be empty.
</p>
)}
</TextField>
</Grid>
</Grid>
</CardContent>
<CardContent sx={{ display: "flex", justifyContent: "right" }}>
<Button variant="outlined" type="submit">
{buttonText}
</Button>
</CardContent>
<div className="text-left">
{showSuccessMessage && (
<p className="text-green-500 font-semibold text-sm my-2">
Thankyou! Your Message has been delivered.
</p>
)}
{showFailureMessage && (
<p className="text-red-500">
Oops! Something went wrong, please try again.
</p>
)}
</div>
</form>
</Paper>
</Box>
</Container>
</>
);
};
export default Contact;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>