How to use Nodemailer in Next Js
next js|

Ayush

Arya

|

Feb 08, 2024

How to use Nodemailer in Next JS


Harnessing the Power of Nodemailer in Next.js: A Step-by-Step Guide

Are you looking to supercharge your Next.js application with the ability to send emails seamlessly? Look no further! In this tutorial, we'll explore how to integrate Nodemailer, a popular Node.js module, into your Next.js project. By the end of this guide, you'll have a robust contact form that not only captures user inquiries but also sends informative emails to both you and the user.

Why Nodemailer?

Nodemailer simplifies the process of sending emails using Node.js. Its versatility and ease of use make it an ideal choice for applications built with frameworks like Next.js. In this guide, we'll focus on incorporating Nodemailer into a contact form within a Next.js project.

The Power of Nodemailer in Next.js

Imagine a scenario where you not only capture user inquiries but also engage with them through personalized email responses. That's precisely what we aim to achieve with Nodemailer in Next.js. Let's break down the steps to harness this power for your application.

Step 1: Installation and Configuration

First things first, ensure you have Nodemailer installed in your Next.js project. Use the command mentioned above for a smooth installation process.

1npm install nodemailer

Step 2: Setting Up Nodemailer Transporter

The createTransport function sets up the Nodemailer transporter. In our example, we've chosen Gmail as the email service. However, you can configure it to work with other services as per your preference.

1const transporter = nodemailer.createTransport({ 2 service: "Gmail", 3 auth: { 4 user: process.env.EMAIL, 5 pass: process.env.SECRET_KEY, 6 }, 7});

Step 3: Crafting Informative Emails

The mailOptions and mailOptions2 objects define the content of the emails. The first email includes the user's details and is sent to your specified email address. The second email serves as a thank-you note and is sent to the user.

Step 4: Sending Emails

The magic happens with the sendMail function. By invoking this function on the transporter, you initiate the process of sending the emails. The asynchronous nature ensures a smooth flow, and errors are handled gracefully.

1await transporter.sendMail(mailOptions); 2await transporter.sendMail(mailOptions2);

Step 5: Error Handling

In the event of any errors during the email send process, the code catches them, allowing you to respond appropriately.

1try { 2 // Sending emails 3} catch (error) { 4 // Handling errors 5}

Conclusion

By integrating Nodemailer into your Next.js project, you've unlocked a new level of interaction with your users. The ability to seamlessly send personalized emails not only keeps you informed but also enhances the user experience. Feel free to customize the code further to align it with your specific use case.

Complete Code

For your convenience, here's the complete code you can use in your Next.js project:

1//pages/api/contact.js 2import nodemailer from "nodemailer"; 3 4export default async function handler(req, res) { 5 if (req.method === "POST") { 6 const { fullname, email, phone, msg } = req.body; 7 8 // Create a Nodemailer transporter 9 const transporter = nodemailer.createTransport({ 10 service: "Gmail", 11 auth: { 12 user: process.env.EMAIL, 13 pass: process.env.SECRET_KEY, 14 }, 15 }); 16 17 // Create a Nodemailer email message 18 const mailOptions = { 19 from: process.env.EMAIL, 20 to: process.env.EMAIL, 21 subject: "Take advantage of the services", 22 html: `<!DOCTYPE html> 23 <html> 24 <head> 25 <meta charset="utf-8"> 26 <meta name="viewport" content="width=device-width, initial-scale=1"> 27 <title>Table Email Template</title> 28 <style type="text/css"> 29 /* Add your custom styles here */ 30 body { 31 font-family: Arial, sans-serif; 32 background-color: #f2f2f2; 33 padding: 50px; 34 } 35 h1 { 36 font-size: 36px; 37 color: #333; 38 text-align: center; 39 margin-bottom: 50px; 40 } 41 table { 42 width: 100%; 43 border-collapse: collapse; 44 margin-bottom: 50px; 45 } 46 th, 47 td { 48 padding: 10px 20px; 49 text-align: left; 50 border-bottom: 1px solid #ddd; 51 } 52 th { 53 background-color: #333; 54 color: #fff; 55 font-size: 18px; 56 } 57 td { 58 font-size: 16px; 59 color: #555; 60 } 61 62 </style> 63 </head> 64 <body> 65 <h1>Your Recent Details</h1> 66 <table> 67 <thead> 68 <tr> 69 <th>FUll Name</th> 70 <th>Email</th> 71 <th>Phone</th> 72 <th>Massege</th> 73 </tr> 74 </thead> 75 <tbody> 76 <tr> 77 <td>${fullname}</td> 78 <td>${email}</td> 79 <td>${phone}</td> 80 <td>${msg}</td> 81 </tr> 82 83 </tbody> 84 </table> 85 </body> 86 </html> 87 `, 88 }; 89 90 // Create a Nodemailer email message for the second email 91 const mailOptions2 = { 92 from: process.env.EMAIL, 93 to: email, 94 subject: "Take advantage of the services", 95 html: `<!DOCTYPE html> 96 <html> 97 <head> 98 <meta charset="utf-8"> 99 <meta name="viewport" content="width=device-width, initial-scale=1"> 100 <title>Thank You Email Template</title> 101 <style type="text/css"> 102 /* Add your custom styles here */ 103 body { 104 font-family: Arial, sans-serif; 105 background-color: #f2f2f2; 106 padding: 50px; 107 text-align: center; 108 } 109 h1 { 110 font-size: 36px; 111 color: #333; 112 margin-bottom: 20px; 113 } 114 p { 115 font-size: 18px; 116 color: #555; 117 line-height: 1.5; 118 margin-bottom: 50px; 119 } 120 .thank-you-icon { 121 width: 100px; 122 height: 100px; 123 margin: 0 auto; 124 background-image: url(https://via.placeholder.com/100x100); 125 background-repeat: no-repeat; 126 background-position: center; 127 background-size: contain; 128 } 129 .btn { 130 display: inline-block; 131 padding: 10px 20px; 132 font-size: 18px; 133 color: #fff; 134 background-color: #333; 135 border-radius: 20px; 136 text-decoration: none; 137 } 138 </style> 139 </head> 140 <body> 141 <div class="thank-you-icon"></div> 142 <h1>Thank You for details!</h1> 143 <a href="theclockmedia.tech" class="btn">Learn More</a> 144 </body> 145 </html> 146 `, 147 }; 148 149 try { 150 // Send the first email 151 await transporter.sendMail(mailOptions); 152 153 // Send the second email only if the first email is successful 154 await transporter.sendMail(mailOptions2); 155 156 return res.status(200).json({ 157 message: "Thank you for contacting us!", 158 }); 159 } catch (error) { 160 console.error(error); 161 return res.status(500).send({ 162 msgType: "error", 163 message: "Check fields.....", 164 }); 165 } 166 } else { 167 return res.status(405).send({ 168 msgType: "error", 169 message: "Method not allowed", 170 }); 171 } 172} 173

Also Read : You may need a contact form, here's the code!

Wrapping Up

In this tutorial, we've explored the integration of Nodemailer into a Next.js project, creating a robust contact form with the capability to send informative emails. Feel free to adapt and enhance this code to fit your application's needs.

That's it! You now possess the knowledge to integrate Nodemailer seamlessly into your Next.js application. If you have any questions or want to further customize the implementation, feel free to explore Nodemailer's documentation for additional features and configurations. Happy coding!


Popular Blog Categories


Contact Me

Phone

Discuss A Project Or Just Want To Say Hi?
My Inbox Is Open For All.

Mail : techayu001@gmail.com

Chatbot