如何在无TypeScript的React项目中使用SMTP.js发送邮件?
在React(非TypeScript)中使用SMTP.js实现联系表单的可行方案
先理清安装误区
SMTP.js和Swiper这类UI库的使用逻辑不一样,它主要通过CDN引入或者轻量npm包方式使用,不是依赖工程化构建的组件库。下面是两种可行的实现方式:
方式1:CDN引入(最稳妥)
- 在项目根目录的
public/index.html中添加SMTP.js的CDN脚本:
<script src="https://smtpjs.com/v3/smtp.js"></script>
- 编写React联系表单组件(函数组件示例):
import { useState } from 'react'; function ContactForm() { const [formData, setFormData] = useState({ name: '', email: '', message: '' }); const handleInputChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); }; const handleFormSubmit = (e) => { e.preventDefault(); // 调用SMTP.js发送邮件 Email.send({ Host: 'smtp.gmail.com', // 替换为你的SMTP服务器,比如QQ邮箱是smtp.qq.com Username: 'your-email@xxx.com', // 你的发件邮箱 Password: 'your-app-specific-password', // 注意:Gmail需用应用专用密码,QQ邮箱用授权码 To: 'your-receive-email@xxx.com', // 收件邮箱 From: formData.email, // 表单填写的用户邮箱 Subject: `来自${formData.name}的联系消息`, Body: ` 姓名:${formData.name} 用户邮箱:${formData.email} 消息内容:${formData.message} ` }).then(res => { alert(res === 'OK' ? '邮件发送成功!' : `发送失败:${res}`); // 清空表单 setFormData({ name: '', email: '', message: '' }); }).catch(err => { console.error('发送出错:', err); alert('发送失败,请稍后重试'); }); }; return ( <form onSubmit={handleFormSubmit} style={{ maxWidth: '500px', margin: '2rem auto' }}> <div style={{ marginBottom: '1rem' }}> <label htmlFor="name">姓名:</label> <input id="name" type="text" name="name" value={formData.name} onChange={handleInputChange} required style={{ width: '100%', padding: '0.5rem', marginTop: '0.3rem' }} /> </div> <div style={{ marginBottom: '1rem' }}> <label htmlFor="email">邮箱:</label> <input id="email" type="email" name="email" value={formData.email} onChange={handleInputChange} required style={{ width: '100%', padding: '0.5rem', marginTop: '0.3rem' }} /> </div> <div style={{ marginBottom: '1rem' }}> <label htmlFor="message">消息:</label> <textarea id="message" name="message" value={formData.message} onChange={handleInputChange} rows="5" required style={{ width: '100%', padding: '0.5rem', marginTop: '0.3rem' }} /> </div> <button type="submit" style={{ padding: '0.6rem 1.2rem', backgroundColor: '#007bff', color: 'white', border: 'none', borderRadius: '4px' }}> 发送消息 </button> </form> ); } export default ContactForm;
方式2:npm包安装
如果你习惯用npm管理依赖,可以安装官方提供的包:
npm install smtpjs
然后在组件中直接导入使用,代码逻辑和上面一致,只需要替换顶部的引入:
import Email from 'smtpjs';
关键注意事项
- 绝对不要在前端直接暴露邮箱密码! 上面的示例仅用于演示,生产环境请通过后端接口转发邮件,避免密码泄露。
- 主流邮箱(Gmail、QQ、163)需要开启SMTP服务,并且使用授权码/应用专用密码代替登录密码(比如Gmail开启两步验证后生成应用专用密码,QQ邮箱在设置里生成授权码)。
- 如果遇到发送失败,先检查SMTP服务器地址、端口(默认465/587)、账号密码是否正确,以及邮箱是否允许第三方客户端登录。
内容的提问来源于stack exchange,提问作者Williams Joseph
相关产品推荐
相关产品推荐

