index

Creating Next js Starting ProjectCreating Main PageCreating Send Mail ApiFinishing frontend WorkCode

How Send Email in next js app With Email js module?

Hello There, In this blog i will explain you that how you can send mail in the next js app with help of the email js node module. So, In node js the nodemailer module is most of the time use for sending the mail, but in production nodemailer sometimes not able to send the mail. This is an Error or issue hear. Also this hash solution but i am find the one of the best alternatives to this is email js. Email-js is a node module which use for sending mail and also very easy and fast.

So, In this post we are going to build a next js app which takes user email as input and sends mail to the user. Hope You Link It.

Creating Next js Starting Project

npx create-next-app
Bash

Run Aboue Command in the terminal and then just give the project name. Than run npm run dev for see app is running fine.

npm  run dev
Bash

Than Install axios and email-js for sending the mail

npm i emailjs axios
Bash

Creating Main Page

Know replace index.js app to code given below


import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { useState } from 'react'
import axios from 'axios'
 
export default function Home() {
 
 const [email,setEmail]=useState('')
 const SendMail = async (e)=>{
   e.preventDefault();
console.log('call')
 }
 
 return (
   <div className={styles.container}>
     <Head>
       <title>Create Next App</title>
       <meta name="description" content="Generated by create next app" />
       <link rel="icon" href="/favicon.ico" />
     </Head>
    
 
     <main className={styles.main}>
       <form>
      <input type="email" placeholder="Enter Mail" required value={email} onChange={(e)=>setEmail(e.target.value)}></input>
      <button onClick={SendMail}>Send</button>
        </form>
     </main>
   </div>
 )
}

JavaScript

We have one useState email which is used for store user email and when the user click on the send button the SendMail Function will call.

Till this point you can see project like below and when you Enter mail and click send you can see output call in console.

1

Creating Send Mail Api

Next js is Used the server-side rendering and we can create api and make request to that api in client side. Let’s create api for send the mail.

Add email.js file to api folder

Enter bellow Code to file

export default function handler(req, res) {
res.status(200).end(JSON.stringify({ message:'Send Mail' }))
}

JavaScript

Just Open http://localhost:3000/api/email this link in browser and you can see Json Out Put on Screen.

2

1.First We Import For Send SMTPClient Smtp service mail (like gmail)

import { SMTPClient } from 'emailjs';
 
JavaScript
  1. Than We have to create client object by passing you email and password
 const client = new SMTPClient({
   user: process.env.mail,
   password: process.env.password,
   host: 'smtp.gmail.com',
   ssl:true
 });
JavaScript

3.Than with the help of client.send() method we can send mail

 
 client.send(
     {
       text: `Just for testing purpose`,
       from: process.env.mail,
       to: email,
       subject: 'testing emailjs',
      
     }
     )
JavaScript

email.js file

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
 
import { SMTPClient } from 'emailjs';
 
 
export default function handler(req, res) {
 
 const {email}=req.body;
 // console.log(process.env)
 
 const client = new SMTPClient({
   user: process.env.mail,
   password: process.env.password,
   host: 'smtp.gmail.com',
   ssl:true
 });
 
 try{
 
  
   client.send(
     {
       text: `Just for testing purpose`,
       from: process.env.mail,
       to: email,
       subject: 'testing emailjs',
      
     }
     )
   }
 catch(e){
   res.status(400).end(JSON.stringify({ message:"Error" }))
   return;
 }
 
 res.status(200).end(JSON.stringify({ message:'Send Mail' }))
}
JavaScript

So, Our Api, For Sending mail is finish.

Finishing frontend Work

In SendMail Function we are gointing to make post request to email api with the help of axios.

Add In SendMail Function

 axios.post('http://localhost:3000/api/email',{email})
   .then(
    
   (res)=>{
     alert('Send Mail To You')
     setEmail('')
 
   }
 
   ).catch(
     (e)=>console.log(e)
   )

JavaScript

And that's it you are successfully able to create an email send app in next js.

Code

index .js

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { useState } from 'react'
import axios from 'axios'
 
export default function Home() {
 
const [email,setEmail]=useState('')
 
const SendMail = async (e)=>{
   e.preventDefault();
   console.log('call')
   axios.post('http://localhost:3000/api/email',{email})
   .then(
    
   (res)=>{
     alert('Send Mail To You')
     setEmail('')
 
   }
 
   ).catch(
     (e)=>console.log(e)
   )
 }
 
 return (
   <div className={styles.container}>
     <Head>
       <title>Create Next App</title>
       <meta name="description" content="Generated by create next app" />
       <link rel="icon" href="/favicon.ico" />
     </Head>
    
 
     <main className={styles.main}>
       <form>
      <input type="email" placeholder="Enter Mail" required value={email} onChange={(e)=>setEmail(e.target.value)}></input>
      <button onClick={SendMail}>Send</button>
        </form>
     </main>
   </div>
 )
}
JavaScript

email.js

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
 
import { SMTPClient } from 'emailjs';
 
export default function handler(req, res) {
 
 const {email}=req.body;
 // console.log(process.env)
 
 const client = new SMTPClient({
   user: process.env.mail,
   password: process.env.password,
   host: 'smtp.gmail.com',
   ssl:true
 });
 
 try{
 
  
   client.send(
     {
       text: `Just for testing purpose`,
       from: process.env.mail,
       to: email,
       subject: 'testing emailjs',
      
     }
     )
   }
 catch(e){
   res.status(400).end(JSON.stringify({ message:"Error" }))
   return;
 }
 
 res.status(200).end(JSON.stringify({ message:'Send Mail' }))
}
JavaScript

Note: Sometimes client.send() methods do not work in production. For Solution of this just use Client.sendAsync(). This will also work in development.


const message = await client.sendAsync({
        text: `Just for testing purpose`,
       from: process.env.mail,
       to: email,
       subject: 'testing emailjs'
,
    });
JavaScript

function foo(bar){
  var a=42,
      b='Prisum';
  return a+bar(b);
      
}
JavaScript

Blog Write By:zeel codder