Nodemailer sending email to an inputted address from a form element: no recipients defined error

27 views Asked by At

I'm creating a form to enable a user to enter their email address for a message to be sent to it.

This is my first time with node js and nodemailer, though I have some javascript experience.

I have problem solved my way though most of the errors that have come my way but this one has me really stuck! I am hoping some devs or coders with more experience can help me out.

After looking under network in the browser development tools, it seems that the form data is being sent with the name "send-email" instead of "email". This discrepancy between the form field name and the expected field name in the server-side code (const { email } = req.body;) is likely causing the email field to be undefined.

Note that the network payload shows the correct email (whatever is inputted).

To solve this, I added an attribute of name="email" to the child input of the parent from in my html (there is only one form with one input).

That didn't work (no change to 'Error sending email: Error: No recipients defined' terminal error or 'something went wrong' console error).

Here is server-side javascript 'app.js':

const express = require('express');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }));

// Allow requests from a specific origin
app.use(cors({
  origin: 'http://127.0.0.1:5500'
}));

// Serve static files from the public directory
app.use(express.static('public'));

// Handle form submission
app.post('/send-email', async (req, res) => {

    console.log('Request Body:', req.body);

    const { email } = req.body;
    console.log('Recipient Email:', email);

    try {
        // Create a transporter
        const transporter = nodemailer.createTransport({
            service: 'Gmail',
            auth: {
                user: '[email protected]',
                pass: 'my app password'
            }
        });

        // Email content
        const mailOptions = {
            from: '[email protected]'
            to: email, // Receiver's email address (from the form input)
            subject: 'Happy Birthday!',
            text: "Your days have grown weary and your purpose on this planet is unclear. At 33, the time has come. Click here to reveal all the answers you've been waiting for." // Link within email to be added later
        };

        // Send email
        const info = await transporter.sendMail(mailOptions);
        console.log('Email sent: ' + info.response);
        res.send('Email sent successfully');
    } catch (error) {
        console.error('Error sending email:', error); // Log the error
        res.send('Error: Something went wrong. Please try again.');
    }
});

// Start the server
app.listen(port, () => {
    console.log(`Server is listening on port ${port}`);
});`

Here is the excerpt from my client-side javascript 'script.js' relevent to the sending of the email:

 function goFlower4() {
    update(locations[2]);
    for (let button of responseButtons) {
        button.style.display = "none";
    }
    form.style.display = 'inline-block';
    
    // Prevent default form submission behavior
    form.addEventListener('submit', function(event) {
        event.preventDefault();

        // Code to handle form submission
        const formData = new FormData(this);

        fetch('http://localhost:3000/send-email', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            // Log the response from the server
            console.log(data); 

            if (data === 'Email sent successfully') {
                // Email sent successfully
                console.log('Email sent successfully');
                // Add any additional actions you want to perform on success
            } else {
                // Error occurred
                console.error('Error: Something went wrong');
            }
        })
        .catch(error => {
            // Error occurred during fetch
            console.error('Error:', error);
        });
    });
}`

and here is my html 'index.html':

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Link</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <img id="flower" src="https://lh3.googleusercontent.com/pw/AP1GczOBvUYf86NutEIv7I-gBpM64pqsGLiOo73UezRnBX8NZqyZpiObTsflckVn_SfStfYK5seycI8h3FPp53ls2Da59GoznQoQhoIRpLe8974JYy6uDGsZ=w593-h315-p-k" alt="flower1"/>
    <br>
    <h2>You say:</h2>
    <button type="button" class="response" id="response1">Hello!</button>

    <form id="form" action="/send-email" method="post" name>
        <label for="email">My email address is </label>
        <input type="email" id="email" name="email" autocomplete="on" required></input>
        <button type="submit" id="submit">send</button>
    </form>
    
    <script src="script.js"></script>
</body>
</html>   `        

I appreciate any and all attempts to help me problem solve this bug!

0

There are 0 answers