求基于SMTP的JavaScript网站联系页邮件发送实现代码
Hey there! Let's work through adding email functionality to your contact form. First off, a quick heads-up: you can't send emails directly from client-side JavaScript via SMTP—browsers block this for security reasons. You'll need either a simple backend service or a third-party API to handle the actual email sending. Below are two straightforward approaches you can use:
Approach 1: Build a Backend with Node.js + Nodemailer
This is a great option if you want full control over the email sending process. We'll use Node.js to create a small backend endpoint that receives form data and sends the email via SMTP.
Step 1: Set Up the Backend Project
- Initialize a new Node.js project:
npm init -y - Install required dependencies:
npm install express nodemailer cors
Step 2: Backend Code (server.js)
const express = require('express'); const nodemailer = require('nodemailer'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json()); // Configure SMTP transporter (replace with your email service details) const transporter = nodemailer.createTransport({ service: 'Gmail', // Can use Outlook, QQ Mail, or other supported services auth: { user: 'your-sender-email@gmail.com', // Your email address pass: 'your-app-specific-password', // For Gmail, use an app-specific password (not your main password) }, }); // Endpoint to handle form submissions app.post('/send-contact-email', (req, res) => { const { phone, email, message } = req.body; const mailOptions = { from: email, // The user's provided email to: 'your-target-email@example.com', // Your email to receive messages subject: `New Contact Message from ${email}`, text: `Phone Number: ${phone}\nUser Email: ${email}\nMessage:\n${message}`, }; // Send the email transporter.sendMail(mailOptions, (error, info) => { if (error) { console.error('Email send error:', error); res.status(500).send('Failed to send your message. Please try again later.'); } else { console.log('Email sent successfully:', info.response); res.status(200).send('Your message has been sent! We\'ll get back to you soon.'); } }); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Step 3: Frontend Form Code
<form id="contactForm"> <div class="form-group"> <label for="phone">Phone Number:</label> <input type="tel" id="phone" required> </div> <div class="form-group"> <label for="email">Your Email:</label> <input type="email" id="email" required> </div> <div class="form-group"> <label for="message">Message:</label> <textarea id="message" rows="5" required></textarea> </div> <button type="submit">Send Message</button> </form> <script> const contactForm = document.getElementById('contactForm'); contactForm.addEventListener('submit', async (e) => { e.preventDefault(); const phone = document.getElementById('phone').value; const email = document.getElementById('email').value; const message = document.getElementById('message').value; try { const response = await fetch('http://localhost:3000/send-contact-email', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ phone, email, message }), }); const result = await response.text(); alert(result); contactForm.reset(); // Clear the form after submission } catch (error) { console.error('Submission error:', error); alert('Something went wrong. Please check your connection and try again.'); } }); </script>
Key Notes for This Approach:
- For Gmail, enable 2-step verification and generate an app-specific password (never use your main account password).
- In production, store sensitive credentials (email, password) in environment variables using a package like
dotenv—don't hardcode them! - Deploy your backend to platforms like Heroku, Vercel, or Netlify for public access.
Approach 2: Use EmailJS (No Backend Required)
If you don't want to build and maintain a backend, EmailJS is a great third-party tool that lets you send emails directly from the frontend.
Step 1: Set Up EmailJS
- Create an EmailJS account (search for it online)
- Add an email service (e.g., Gmail) and get your Service ID
- Create an email template (define recipient, subject, and message structure) and get your Template ID
- Copy your User ID from your EmailJS dashboard
Step 2: Frontend Code
<form id="contactForm"> <div class="form-group"> <label for="phone">Phone Number:</label> <input type="tel" id="phone" required> </div> <div class="form-group"> <label for="email">Your Email:</label> <input type="email" id="email" required> </div> <div class="form-group"> <label for="message">Message:</label> <textarea id="message" rows="5" required></textarea> </div> <button type="submit">Send Message</button> </form> <!-- Load EmailJS script --> <script src="https://cdn.jsdelivr.net/npm/emailjs-com@3/dist/email.min.js"></script> <script> // Initialize EmailJS with your User ID emailjs.init('YOUR_USER_ID'); const contactForm = document.getElementById('contactForm'); contactForm.addEventListener('submit', async (e) => { e.preventDefault(); try { const result = await emailjs.send( 'YOUR_SERVICE_ID', // Replace with your Service ID 'YOUR_TEMPLATE_ID', // Replace with your Template ID { phone: document.getElementById('phone').value, user_email: document.getElementById('email').value, message: document.getElementById('message').value, recipient_email: 'your-target-email@example.com' // Or set this in your EmailJS template } ); console.log('Message sent:', result.text); alert('Your message has been sent successfully!'); contactForm.reset(); } catch (error) { console.error('Send error:', error); alert('Failed to send your message. Please try again later.'); } }); </script>
Key Notes for This Approach:
- The free tier of EmailJS has sending limits, which is perfect for small sites.
- Your User ID, Service ID, and Template ID are safe to expose publicly—EmailJS restricts usage to your configured services and templates.
内容的提问来源于stack exchange,提问作者Ajay Patel

