DEV Community

Cover image for 3 ways to send emails with only few lines of code and Gmail - Javascript - Part 1
François
François

Posted on • Updated on

3 ways to send emails with only few lines of code and Gmail - Javascript - Part 1

We will see how to send a simple email with the help of three different programming languages: Javascript, Ruby and Python
Before you start you need to create a Gmail account.
Do not forget to accept and allow the "Less secure apps" access in order use your scripts with your Gmail smtp connection.
I'll let you do this on your own, you don't need a tutorial for this
😜

Javascript 🚀

  • For the first script, we are going to use the Nodemailer module:
yarn add nodemailer
Enter fullscreen mode Exit fullscreen mode
  • Require or import the module into your index.js:
const nodemailer = require('nodemailer')
Enter fullscreen mode Exit fullscreen mode
  • Initialize the mailer with our Gmail account info:
// Gmail account info
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});
Enter fullscreen mode Exit fullscreen mode
  • Create your email:
// Email info
const mailOptions = {
  from: 'youremail@gmail.com',
  to: 'myfriend@yopmail.com',
  subject: 'Sending email using Node.js',
  text: 'Easy peasy lemon squeezy'
};
Enter fullscreen mode Exit fullscreen mode
  • Sending your email:
// Send email and retrieve server response
transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});
Enter fullscreen mode Exit fullscreen mode

Here the final code:

const nodemailer = require('nodemailer')

// Gmail account info
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

// Email info
const mailOptions = {
  from: 'youremail@gmail.com',
  to: 'myfriend@yopmail.com',
  subject: 'Sending email using Node.js',
  text: 'Easy peasy lemon squeezy'
};

// Send email 📧  and retrieve server response
transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});
Enter fullscreen mode Exit fullscreen mode

Javascript buddy 🤝

Javascript buddy

Table of contents

Top comments (3)

Collapse
 
drsimplegraffiti profile image
Abayomi Ogunnusi

Thanks this is nice

Collapse
 
carlosg33558699 profile image
Carlos Gonzalez

Thanks!

Collapse
 
jameshackett profile image
JamesHackett

Wow, thanks this is interesting. I will follow you