Building Interactive Email Sending Functionality with vue js and Express

Building-Interactive-Email-Sending-Functionality-with-vue-js-and-Express

To implement a form submission that sends an email using Vue.js, you’ll need a server-side component to handle the email sending. In this example, I’ll provide a step-by-step guide using Vue.js for the front end and a simple Node.js server with Express to handle the form submission and send the email. Please note that you’ll need Node.js installed on your server for this example.

Step 1: Set Up a Vue.js Project

# Install Vue CLI globally if not installed
npm install -g @vue/cli

# Create a new Vue project
vue create vue-email-form
cd vue-email-form

Step 2: Install Axios

Axios will be used to make HTTP requests from the Vue.js front end to the server.

npm install axios

Step 3: Create a Vue Component

In the ‘src/components’ directory, create a new component for your form. For example, EmailForm.vue.






Step 4: Set Up Express Server

Create a new file ‘server.js’ in your project’s root directory for the server.

npm install express nodemailer body-parser
const express = require('express');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(bodyParser.json());

app.post('/api/send-email', (req, res) => {
  const { email, message } = req.body;

  // Replace these with your email server details
  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'your-email@gmail.com',
      pass: 'your-email-password'
    }
  });

  const mailOptions = {
    from: 'your-email@gmail.com',
    to: email,
    subject: 'Subject of the Email',
    text: message
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.error('Error sending email:', error);
      res.status(500).send('Error sending email');
    } else {
      console.log('Email sent:', info.response);
      res.status(200).send('Email sent successfully');
    }
  });
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

Replace ‘your-email@gmail.com’ and ‘your-email-password’ with your email address and password. Note that using your main email and password is not recommended for production; instead, consider using an app-specific password or OAuth for security.

Step 5: Run Your Vue App and Express Server

# In one terminal window, run the Vue app
npm run serve

# In another terminal window, run the Express server
node server.js

Visit http://localhost:8080 in your browser and test the form submission. The form data will be sent to the Express server, which will use Nodemailer to send an email.

Remember to secure your email credentials and consider additional security measures, such as using environment variables for sensitive information, especially in a production environment.

Related Posts