How to Send Emails with Next JS and Nodemailer
Вставка
- Опубліковано 11 вер 2024
- UPDATED 2024 - I no longer recommend using Nodemailer for sending emails. Instead use Resend (resend.com), as they make it very easy to send emails and have a generous free tier.
In this video you'll learn how to build a contact form in Next JS that sends emails using API routes and Nodemailer. I'll be using a gmail account in this video, but it will work with other email providers as well.
Starting Files: github.com/nik...
Finished Files: github.com/nik...
Github: github.com/nik...
Support Me: www.buymeacoff...
Contact Me: nikitadev292@gmail.com
#nextjs #react #nodemailer
Dude you're such a lifesaver. I was making this way too complicated trying to use the Gmail API and Express and knew there had to be an easier way with using Next. Thank you!
I wanted to ask, in my application I'm wanting to take the users email that they input and send the mail directly to them instead of myself. How would i pass that value from the form into mailOptions?
you can remove the "to" prop from the mailOptions and just set it in the sendMail() call in the handler. In that case, you would be setting the "to" property on the fly, on every request, with whatever the user passed to you in the body.
If you take this approach, I would add stronger email validation (using a validation library) to ensure that the user sent a valid email before calling sendMail()
@@nikita-dev I came across your video wanting to learn about nodemailer and I ended up learning alot more, I'm using zod in my handler to validate emails would think this is a good way to validate the email? looking forward for more videos about nextjs, thank you so much
No problem! And yes, Zod should be sufficient for email validation
Bro, JUST the same thing I was trying to do. I spent 4 hours and got just frustrated and dropped the idea.
after 5 hours of trying different options, i finally found the best one
it was fun making this work on next.js 13, lot of new things i learn within 2 hour it take for me to finish it. thanks bro
Hello keyonlevis. i have been trying to make it work on nextjs 13. However, i have not been able to get it right. Please kindly help me with your code. I will deeply appreciate you. Thanks
Hey Nikita, you guided me in the right way, I was struggling with this topic, Thank you
Great tutorial, thanks for posting this. There is a lot of ends and outs to this process and this video helped give a great guide to getting me toward the track I need!
I’m glad it was helpful!
Thank you so much for this. Was bashing my head against a wall trying to figure out how to send an email without using a paid service. What I'm wondering now is how, whoever submitted the form, they get a confirmation email as well.
you can call the sendMail method again, but just override the "to" property with the user's email that they input. For example:
await transporter.sendMail({
...mailOptions,
...generateEmailContent(data),
subject: data.subject,
to: RECIPIENT_EMAIL
});
(replace RECIPIENT_EMAIL with the data that was passed from the user)
I've been trying to integrate this feature ever since, but I couldn't find anything that worked for me. Thanks a lot for sharing
One issue I had was that my windows firewall was blocking outgoing connections on port 465 which is what gmail uses. When running my app locally, when I temporarily disable the firewall, it works.
Thank you, I ran into issue with Express and whatnot and it just got too complicated. This makes way more sense.
Great explaination too!
thank you, I'm glad it was helpful!
This is exactly what I've been looking for! ❤
Superb content. Clear and slick. Keep it up!
An elegant solution, and well explained. Thanks!
Perfectly explained and definetely a huge help on my learning journey as a developer, Thank You!!
Awesome tutorial!! Well explained and you saved me hours for implementing a email handler!!
Awesome video, my guy. You the man!!!! Keep em coming
Thanks for the help!! Amazing tutorial.😁
Great explanation! Straight to the point.
Thank you so much for sharing your experience, Sir.
Thank you, any possibility of a follow up to this video, migrating to the Nextjs 13 App directory? I am having an absolutely impossible time trying to implement the teachings of this video to their new system of API usage. Much, much appreciated.
Hi Onelight! I like your solution since I was trying to get a functionality like this using services like sendgrid but all of these require you to have a private email domain which I can't affort right now.
But I do have a question, I implemented your solution almost identically to yours with almost the same validations: isn't it kind of a vulnerability that an user can spam the send button or creating a script to completely flood your inbox? If that's the case, what can I do to prevent that from happening?
Wow, Thank you so much!
Why is nodemailer not sending the email when deploying on Vercel?
it is likely an issue with your environment variables
I followed this video verbatim and it works flawlessly. Well, I adapted it a bit to use TailwindCSS for the contact form but still works great... locally. When I push to my production deployment on Vercel and test it live, it does not work. I added the environment variables (EMAIL & EMAIL_PASS) to Vercel settings thinking that was the issue, but still no fix. Can anybody help me with this? Does anybody have similar issues?
EDIT: Needed to perform a new deployment after adding Envrionment Variables to Vercel in order to update the site with the variables. Ran a test and it works!! Thank you!
hi Evan, could you explain a little better how you made it work? having the same issue here, but on netlify
@@pedro.sh101 I was only updating locally so in order to update in production I needed to push a new deployment to vercel in order for the environment variable to take place.
I had to do the same thing!
THIS TUTORIAL WAS HELPFUL !!
Super helpful, thank you very much. Keep up the good work!
thank you!
hi i am facing issue with fetch the contact api . 400 bad request coming
export const sendContactForm = async (data) =>
fetch('api/contact', {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json", Accept: "application/json" },
}).then((res) => {
if (!res.ok) throw new Error("Failed to send message");
return res.json();
});
Thank you for create amazing clearly tutorial. So helpful for me.
Its not working on my end... i followed everything
what part specifically is not working?
everything works perfectly fine, just a question, is this api/contact public for everyone when we host it? Is there a risk of this data being leaked?
Hey, thanks for the video! Could you also make a tutorial on how to additionally send an attachment via this form and nodemailer?
Please let me know what you think, I Have looked up on the internet and could not find much help, there are also not answered questions about it on stack overflow, so this video could help a lot of people
I will definitely consider it!
Thank you!
@@nikita-dev :(
You are a legend. Thank you!
Dude you're great. This helped me a lot❤❤❤❤
Also thanks for posting repo it annoys me when people dont do so lol
Very helpful. Subbed. Thank you.
If using newer versions of Next.js, would you just add "use client" to the top? Or would you do this a different way?
Great!
This was really really helpful thanks
Thanks!
thank you so much bro lots of love . it helped me in my porject. 🥰
I hope I get a reply from this. I can't seem to accomplish it via using Outlook, it sends me error code 535 5.7.139 Authentication unsuccessful. I'm doing a blind approach on this configuration. Please I do need help on this matter.
Here is a helpful article on using Nodemailer with Outlook: ourcodeworld.com/articles/read/264/how-to-send-an-email-gmail-outlook-and-zoho-using-nodemailer-in-node-js
thanks!
Thank you so much, your video helped me a lot
Thank you so much. Its really helpful
Nice video, It worked perfectly, Thank You
awesome man, thank you
Great tutorial. One question though. I would like to send the automated confirmation email to the client, rather than to myself. How do you adjust the mailOptions function to allow this? Thanks in advance
You would have to overwrite the "to" property in the mailOptions object. You will have to do that dynamically on each request. For example:
await transporter.sendMail({
...mailOptions,
...generateEmailContent(data),
subject: data.subject,
to: RECIPIENT_EMAIL
});
(replace RECIPIENT_EMAIL with the data that was passed from the user)
Thank u so much. Ur video has helped me
Get tutorial! But I have an error on my end. It's saying: Cannot read properties of undefined (reading 'sendMail') at handler. How do I fix this?
it looks like your transporter object is not being imported correctly. Are you exporting from the config/nodemailer.js file?
@@nikita-dev Thank you, I went back and copied exactly what you had and it finally worked. I must have had a typo somewhere. Thank you for responding!! Also, great tutorial not get! lol
@@nikita-dev Would you be willing to give me advise on transferring this to an existing project. I'm now getting an error stating it cannot resolve 'nodemailer'. The error suggest trying a 'preferRelative' . How would I add this to the config/nodemailer file?
did you install the nodemailer package from NPM? (in your other project)
Greate tutorial! How did you solve the problem of sending a message from Vercel hosting?
You just have to make sure your environment variables are set up correctly. If you change them at all, make sure to rebuild the environment so it can pull in the updated values
if I want to change "from" and "to" for differnet mail then this EMAIL_PASS pin is needed for both mail ?? how can i do that?
you will only need to change the EMAIL_PASS variable for the sender's email (the "from" email). Yo don't need a password for the "to" email
Great video, thanks!
Bravo!
Thank you so much for the video, it really helped make my contact form. The only issue that i have is that, even though i have my type="email" on the email input, i can write whatever (without an @) and the email is still sent. It isn't a big problem but i would really appreciate if you could help me with this. Thank you!
how can i add attachment file? and where i need to put the file if i want to send it ?
멋진 튜토리얼 입니다.
Thank you! It worked but HOW do you set up where the sender displays their name in the email and not the "Me" Email?
Hey thanks for the video! I’m having some issues moving to production since the send email function is taking more than 10 sec to run which makes that vercel stop the execution due to limitations on the free plan. Do you think it could be a solution for this? Thanks in advance!
It shouldn't take more than 10sec to run... Im assuming there's an error in your API route. Are you able to check the server logs and see if there are any errors that are logged?
@@nikita-dev It will be returning a 504 because if its hosted on vercel it could be doing a "cold start", causing the resource to time out?
Did you find a solution to this?
@@AdamBakerMTB not really. I ended up using sendgrid.
Appreciate this so much
hi, do you tutorial or other resources that have for file upload in pdf format? thank you
Chakraui updated docs disabled for button is now isDisabled hope it helps✌🏻🔥
Hey!
Error: fs not found from node_modules folder of node mailer
tell me the sulotion
Hi, how to solve Error.can you share
Thank you so muchhh!!
This is not working on nextjs 13. latest version. Please help
about template. is possible if import template email.html to api? not copy all code from template. i mean just import it
Thank you so much!
Awesome thanks.
Could you make a version of this video that does not rely upon chakara?
Thank you for the tutorial! I got everything working until the very end. The contact form works on my localhost but not on my deployment link with Vercel. I keep getting "Failed to send message" using my deployment link. Any idea why?
using the chrome dev tools, there is a network error saying ""Missing credentials for \"PLAIN\""
It is likely an issue with your environment variables. Can you verify that they are set properly and you’re able to access them from the Vercel app? (Create a test endpoint that returns some of the non-sensitive env variables like the email and ensure that you get back the right value)
@@nikita-dev Thank you so much, that did the trick! I needed to add my env variables to my vercel app.
thanks a lot:)
Hey Nikita thanks for this. Im using Nextjs and supabase and im now requiring to use a smtp, for sending sign up and reset emails only, so what do you think is the best way to do about this? Nodemailer + Amazon SES? or can I just use nodemailer alone
Honestly I would recommend just using AWS SES or Resend
@@nikita-dev thanks nikita.
I really appreciate it
Just Awesome
works local but not working on server "gateway timeout 504"
is the spinning annimation part of Chakra-ui or embedded into nexjs?
it's part of Chakra UI
Awesome tutorial. Question: how do we supply env variables in production? Thanks in advance for any help!!
It depends on where you deploy (Netlify, Vercel). There is usually a tab in your configuration settings called "Environment Variables". You should be able to find detailed steps by looking through the docs of the cloud company you are using (to deploy).
but this is basically me messaging me ?
when I check who sent the email it is the user we entered so how can random people mail me for my portfolio website?
You’ll have to rely on the email sent in the form field to know who submitted the contact form. Sure the user can pass a fake or invalid email in that field, but if they really want you to get back to them, it will be a valid email.
If you want the email to come from the user who is actually contacting you, you should use an HTML email link: with href set to: mailto:myemail@gmail.com
This will open the users default email client and allow them to send an email to you directly.
@@nikita-dev thank you very much!
for me, it doesn't work and I don't know why. l receive the message " Failed to send message" also I receive the next Error: Missing credentials for "PLAIN"
This is likely an issue with your environment variables. Are you able to get it working locally by hard coding the values into your nodemailer instance?
Thanks for your great explanation, i would like to ask can i adapt this approach in my project for sending email notification within my workplace for workflow tasks such as approval email notifications when a new request has created by employees ? regards
Yes, you can reuse the same nodemailer client to send emails for various different actions that you want to handle in your app. The only thing that would change is the email content
Error: Connection timeout
code: 'ETIMEOUT',
command: 'CONN'
Please tell me how i can solve this error.
when are you getting this error?
Good job, but I need help if you can. I want to use this form to send email with attachment or embedded image. Nodemailer has an example for it but that example uses locally stored images which is not what I need. I need user to be able to upload picture and send it to email. Please give me some guidance.
You'll have to first store the image somewhere (S3, or whatever cloud provider you're using), then get the public URL to that image and use that to create an image in the email HTML. This logic can all be done in the handler
didn't work for me, Getting this Error Error: Missing credentials for "PLAIN". Please help
this is likely due to an environment variables issue (the nodemailer client is not getting the right email/password values). can you verify that your env variables are set up properly?
Is this possible to setup without using 2F auth? If so, do i just ommit the pass variable? Having some issues with getting it to work. Might have to rabbit hole for the night
honestly I would recommend using Resend instead of Nodemailer
@@nikita-dev isn't resend not free? I'll look into it for sure. thanks man
they have a pretty generous free tier
@@nikita-dev Don't we need to add domain in order to send emails from any place. Would have to buy domains right?
Thank you!!!!
Great video
Very good
Thanks
good job!
Awesome
As far as I could tell, gmail does not support media queries
It sends message undefined undefined to my gmail..how do I fix this?
The stringData comes out as undefined
it works👍
How can I fixed this? thanks
great
I don't want to let user type email, I want to get their email automatically and then send mail by that email, so user get scared from spamming mail
bcz I am using this form for my own portfolio website but user may spam mail me as its not his/her mail
how did you acheive this
@@MrX-ct8dj I added limit so that user can only send 1 mail per hour with the help of local storage.
When user sends mail, it sets a timestamp to local storage and it checks for this every time before sending mail
anyone having trouble getting their Toast to pop up when an e-mail is sent?
Sir when I deploy this aap to firebase hosting nodemailer does not send an email..please reply
This is because firebase hosting only supports static files (not SSR pages or API routes). It's possible to host your entire Next App (or just API routes) through Firebase functions, but it gets pretty complicated. I would recommend sticking with Vercel or Netlify for deploying NextJS apps. More details here: stackoverflow.com/questions/70992583/nextjs-api-routes-not-working-with-firebase-hosting
@@nikita-dev can we host APIs which build in next js like in api folder to vercel?
yes, Vercel supports SSR and API routes
Can you use this to send to outlook emails?
yup! you can find some examples online: ourcodeworld.com/articles/read/264/how-to-send-an-email-gmail-outlook-and-zoho-using-nodemailer-in-node-js
Everything works great during development, after transferring to amazon amplify it does not work. Who knows how to solve problem?
Here is a helpful doc for deploying SSR Next.js apps:
docs.amplify.aws/guides/hosting/nextjs/q/platform/js/#deploy-and-host-a-hybrid-app-ssg-and-ssr
Some things to note: when you're setting up the build configuration, set the
"Distribution Directory Path" to ".next", and then make sure to add these to the amplify.yml file under:
build:
commands:
- env | grep -e EMAIL -e EMAIL_PASS >> .env.production
- npm run build
and then make sure to set these environment variables for the Amplify app (found under "Advanced Settings" or on the left side bar "Environment Variables")
Hi, thx a lot !, just not working in production. Mail received with "undefined" instead of req.body value
were you able to get it working locally?
@@nikita-dev I'm having the same problem. It works locally but if I deploy to Amplify, it doesn't work. I've tried entering the env variables into Amplify but even then it gives me a 405 error.
@@formorri Same issue here. Could this be gmail blocking the request?
awesome job but, thanks a lot