You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求基于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

  1. Initialize a new Node.js project:
    npm init -y
    
  2. 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

  1. Create an EmailJS account (search for it online)
  2. Add an email service (e.g., Gmail) and get your Service ID
  3. Create an email template (define recipient, subject, and message structure) and get your Template ID
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:00:25