React Native无需打开Gmail应用直接发送用户评论到指定邮箱如何实现
React Native 应用内直接发送用户评论到指定邮箱实现方案
这个需求完全可以实现,无需跳转打开第三方邮箱应用,下面是具体实现方案:
实现方案(推荐后端转发,安全性最高)
这是生产环境唯一推荐的方案,不会泄露你的邮箱相关密钥:
- 先开发一个后端接口,功能是接收前端传入的用户评论内容,服务端通过SMTP配置将内容发送到你指定的两个邮箱,收件人直接固定为你要接收的邮箱即可,无需前端传递。
- 前端在发送按钮的点击事件中,先校验评论内容非空,再请求这个后端接口,接口返回成功后再关闭模态框,可搭配 toast 提示用户发送结果。
如果是个人小项目不想开发后端,也可以使用 react-native-smtp-mailer 第三方库直接在前端调用SMTP发送,但非常不推荐生产环境使用,因为SMTP授权码写在前端代码中很容易被反编译获取,导致邮箱被盗用。
代码修改示例
你的原有代码只需要修改发送按钮的 onPress 逻辑即可:
import React, { useState } from "react" import { StyleSheet, View, Text, TextInput, ToastAndroid } from "react-native" // 导入Toast做提示 import { colors } from "../../theme/Colors" import Fonts from "../../theme/Fonts" import { units } from "../../theme/Units" import ModalButtonWithBackground from "./ModalButtonWithBackground" const StoreReview = (props) => { const [comment, setComment] = useState('') // 新增发送处理函数 const handleSendComment = async () => { const trimComment = comment.trim() if(!trimComment) { ToastAndroid.show('请输入评论内容', ToastAndroid.SHORT) return } try { // 替换为你自己的后端接口地址 const res = await fetch('https://你的接口地址/send_mail', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ comment: trimComment // 可额外添加用户信息、设备信息等参数 }) }) if(res.ok) { ToastAndroid.show('发送成功', ToastAndroid.SHORT) props.onPressCloseModal() setComment('') // 清空输入内容 } else { ToastAndroid.show('发送失败,请稍后重试', ToastAndroid.SHORT) } } catch(e) { console.error('发送请求错误', e) ToastAndroid.show('发送失败,请检查网络', ToastAndroid.SHORT) } } return ( <View style={styles.container}> <Text style={styles.headerText}> We are very sorry about this. Can you share your experiences? </Text> <View style={styles.commentArea}> <TextInput onChangeText={setComment} value={comment} multiline={true} placeholder="请输入你的评论" style={{padding: 10}} // 加个内边距,输入不会贴边 /> </View> <View style={styles.button}> <ModalButtonWithBackground buttonText={'Send'} onPress={handleSendComment} // 替换为新的处理函数 /> </View> </View> ) } const styles = StyleSheet.create({ container: { marginTop: units.height / 144, height: units.height / 2.88, justifyContent: 'space-between', }, headerText: { fontFamily: Fonts.type.bold, fontSize: Fonts.size(20), color: colors.WHITE, textAlign: 'center', marginHorizontal: units.width / 7.87 }, commentArea: { width: units.width / 1.13, height: units.height / 7.2, backgroundColor: colors.WHITE, alignSelf: 'center', borderRadius: 5, }, button: { marginTop: 4 } }) export default StoreReview
模态框视图参考

注意事项
- 后端发送邮件可直接使用对应语言的邮件库,比如Node.js用
nodemailer,Python用yagmail,配置你自己的邮箱SMTP信息即可,收件人固定写你要接收的两个邮箱。 - 绝对不要将邮箱SMTP授权码、密码等敏感信息写在前端代码中,避免被盗用。
内容的提问来源于stack exchange,提问作者SoF
相关产品推荐
相关产品推荐

