ReactJS集成SmtpJs邮件发送API遇语法兼容问题求助
I’ve helped lots of developers work through this exact issue—let’s break down how to get SmtpJS working smoothly in your React form submission handler, and fix those compatibility errors you’re hitting.
Step 1: Load the SmtpJS Script Globally
Unlike plain HTML where you can drop the script tag directly, React needs the SmtpJS library loaded globally so your components can access it.
Add this script tag to the <head> section of your public/index.html file (the main HTML entry point for your React app):
<script src="https://smtpjs.com/v3/smtp.js"></script>
This ensures the Email object is available across all your React components.
Step 2: Build Your React Form with a Working Submission Handler
The most common pitfall is not accessing the global Email object correctly in React’s modular environment. React components don’t automatically recognize global variables unless you reference them via window (or declare them as global for linting purposes).
Here’s a complete, functional example of a React form that uses SmtpJS:
import { useState } from 'react'; // Optional: Declare Email as a global to avoid linting warnings /* global Email */ const ContactForm = () => { const [recipient, setRecipient] = useState(''); const [subject, setSubject] = useState(''); const [message, setMessage] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); try { // Use window.Email to access the global library (or just Email if you added the global comment) const response = await window.Email.send({ Host: "smtp.your-provider.com", // e.g., smtp.gmail.com (note: Gmail requires app passwords now) Username: "your-email@domain.com", Password: "your-smtp-password", // WARNING: Read the security note below! To: recipient, From: "your-email@domain.com", Subject: subject, Body: message }); alert(`Email sent successfully! ${response}`); // Reset form fields after successful send setRecipient(''); setSubject(''); setMessage(''); } catch (error) { alert(`Failed to send email: ${error.message}`); } }; return ( <form onSubmit={handleSubmit} className="contact-form"> <div className="form-group"> <label>Recipient Email:</label> <input type="email" value={recipient} onChange={(e) => setRecipient(e.target.value)} required /> </div> <div className="form-group"> <label>Subject:</label> <input type="text" value={subject} onChange={(e) => setSubject(e.target.value)} required /> </div> <div className="form-group"> <label>Message:</label> <textarea value={message} onChange={(e) => setMessage(e.target.value)} required rows="5" /> </div> <button type="submit" className="submit-btn">Send Email</button> </form> ); }; export default ContactForm;
Fixing Common Errors
"Email is not defined": This happens because React’s module system doesn’t expose global variables by default. Fix it by either:
- Using
window.Emailinstead of justEmail - Adding the
/* global Email */comment at the top of your component to inform linters it’s a global variable
- Using
Uncaught Promise Rejections: SmtpJS returns a Promise, so always wrap the call in
try/catch(or use.then()/.catch()) to handle failures gracefully instead of letting errors crash your app.
Critical Security Note
Never hardcode your SMTP username and password directly in React code! Anyone can inspect your app’s source and steal these credentials. Instead, use SmtpJS’s Secure Token feature:
- Generate a secure token on the SmtpJS website using your SMTP details
- Replace the
Host,Username, andPasswordfields with a singleSecureTokenfield:await window.Email.send({ SecureToken: "your-generated-secure-token", To: recipient, From: "your-email@domain.com", Subject: subject, Body: message });
This keeps your sensitive SMTP credentials hidden.
Bonus: Clean Up Your Code with a Reusable Service
To keep your components tidy, wrap the email logic in a reusable function:
// utils/emailService.js export const sendEmail = async (emailDetails) => { try { const response = await window.Email.send({ SecureToken: "your-secure-token", ...emailDetails }); return { success: true, response }; } catch (error) { return { success: false, error: error.message }; } }; // In your component import { sendEmail } from '../utils/emailService'; const handleSubmit = async (e) => { e.preventDefault(); const result = await sendEmail({ To: recipient, From: "your-email@domain.com", Subject: subject, Body: message }); if (result.success) { alert("Email sent!"); // Reset form } else { alert(`Error: ${result.error}`); } };
内容的提问来源于stack exchange,提问作者Othman El houfi

