I have some form data in one of my Vue components that I want to pass on to my Nodemailer script so that data can be sent as an email. I'm trying to use Axios to do this.
Nothing is happening though as I don't actually know what I'm doing!
The Nodemailer script I have set up works when I execute the file in the command line. What I need is for it to execute when the form in my Vue.js component is submitted.
Here is my Nodemailer script -
"use strict";
const nodemailer = require("nodemailer");
require('dotenv').config();
// async..await is not allowed in global scope, must use a wrapper
async function main() {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: process.env.user, // generated ethereal user
pass: process.env.password, // generated ethereal password
},
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: process.env.user, // sender address
to: process.env.email, // list of receivers
subject: 'Translation Suggestion', // Subject line
text: "Hello world?", // plain text body
html: "<p>Traditional: <br> Simplified: <br> Pinyin: <br> English: "
});
console.log("Message sent: %s", info.messageId);
// Message sent: <[email protected]>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
main().catch(console.error);
And the function being called upon submit in my form component -
<button type="submit" @click="sendEmail" >Suggest</button>
sendEmail () {
axios.post("localhost:3000/send-translation-suggest-email", () => {
this.traditional,
this.simplified,
this.pinyin,
this.english
})
}
CodePudding user response:
To create a REST-API with express.js, first initialize a node.js-project (npm init [-y]
). Then you install express.js
(npm install express
).
When you have your setup, you can create an index.js
-file, the server. In it, you will have to adapt the content of the express Hello World example, so that the route it accepts is not GET /
but POST /send-translation-suggest-email
. Then make sure your server listens to port 3000 (as you specified in the client-side code).
In the listener to POST /send-translation-suggest-email
, you can call the main
-method from your other file (make sure to import the file properly, with node.js
's require
-syntax).
Then, you can call the backend server from the frontend as you wished.