如何使用react.js前端发送电子邮件?

问题描述

我已经创建了一个网站并将其部署(使用react js)在我的网站中,有一个联系表会将客户消息发送到我的工作电子邮件(myname@comany.com)。我知道我无法使用react js发送电子邮件,因为rereact仅处理前端,因此我正在寻找使用nodemailer或其他解决方案的解决方案!我该怎么办?

我尝试了以下教程与Express进行链接:[https://medium.com/@maison.moa/setting-up-an-express-backend-server-for-create-react-app-bc7620b20a61] [1]

我制作了一个用于测试的快速应用程序: 文件夹结构:

client ( created with create-react app )
node_modules
config.js
package.json
package_lock.json
server.js
前端中的

:client / src app.js代码

import React,{ Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Form from './Form.js';

class App extends Component {
state = {
    data: null
  };

  componentDidMount() {
      // Call our fetch function below once the component mounts
    this.callBackendAPI()
      .then(res => this.setState({ data: res.express }))
      .catch(err => console.log(err));
  }
    // Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
  callBackendAPI = async () => {
    const response = await fetch('/express_backend');
    const body = await response.json();

    if (response.status !== 200) {
      throw Error(body.message) 
    }
    return body;
  };

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
      <Form/>
        <p className="App-intro">{this.state.data}</p>
      </div>
    );
  }
}

export default App;

Email.js代码

import React from 'react';
import { Email,Item,A} from 'react-html-email';
export default function InlineLink({name,children}) {
  return (
  <Email title='link'>
    <Item>
       Hello {name}
       <p>helooo</p>
    </Item>
    <Item>
      {children}
    </Item>
  </Email>
)};

Form.js代码

import MyEmail from './Email'
import { renderEmail } from 'react-html-email'
import axios from 'axios';
import React,{ Component } from 'react';

class Form extends Component {

    resetForm(){

        this.setState({Feedback: ''});
    }

    constructor(props) {
        super(props);
        this.state = { Feedback: '',name: 'Name',email: 'email@example.com' };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }

   
  render() {
    return (
        <form className="test-mailing">
        <h1>Let's see if it works</h1>
        <div>
        <textarea
            id="test-mailing"
            name="test-mailing"
            onChange={this.handleChange}
            placeholder="Post some lorem ipsum here"
            required
            value={this.state.Feedback}
            style={{width: '100%',height: '150px'}}
        />
        </div>
        <input type="button" value="Submit" className="btn btn--submit" onClick={this.handleSubmit} />
    </form>
    );
  }
  handleChange(event) {
    this.setState({Feedback: event.target.value})
  };
  handleSubmit(event){

    const messageHtml =  renderEmail(
      <MyEmail name={this.state.name}> {this.state.Feedback}</MyEmail>
    );
    
            axios({
                method: "POST",url:"http://localhost:3000/send",data: {
              name: this.state.name,email: this.state.email,messageHtml: messageHtml
                }
            }).then((response)=>{
                if (response.data.msg === 'success'){
                    alert("Email sent,awesome!"); 
                    this.resetForm()
                }else if(response.data.msg === 'fail'){
                    alert("Oops,something went wrong. Try again")
                }
            })
        }
}
export default Form;
后端中的

server.js代码

const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port,() => console.log(`Listening on port ${port}`));

// create a GET route
app.get('/express_backend',(req,res) => {
  res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});
const nodemailer = require('nodemailer');
const creds = require('./config');

var transport = {
  host: 'smtp.gmail.com',// e.g. smtp.gmail.com
  auth: {
    user: creds.USER,pass: creds.PASS
  }
}

var transporter = nodemailer.createTransport(transport)

transporter.verify((error,success) => {
  if (error) {
    console.log(error);
  } else {
    console.log('All works fine,congratz!');
  }
});
app.use(express.json()); app.post('/send',res,next) => {
    const name = req.body.name
    const email = req.body.email
    const message = req.body.messageHtml
  
  
    var mail = {
      from: name,to: 'mellitir11@gmail.com',subject: 'Contact form request',html: message
    }
  
    transporter.sendMail(mail,(err,data) => {
      if (err) {
        res.json({
          msg: 'fail'
        })
      } else {
        res.json({
          msg: 'success'
        })
      }
    })
  })

config.js代码

module.exports = {
    USER: 'mellitir11@gmail.com',PASS: 'my_email_password',}

即使它显示错误消息“糟糕,出了点问题。请重试” [1]:https://medium.com/@maison.moa/setting-up-an-express-backend-server-for-create-react-app-bc7620b20a61

解决方法

Nodemailer可能会为您解决这个问题,从本质上讲,您将需要一个支持smtp,节点v6或更高版本的电子邮件帐户,以及Nodemailer Documentation(有一个示例),它支持ssl,Oauth身份验证和DKIM。根据您的具体需求,还有其他选项,例如mailgun和mailchimp,它们提供API或PHP或Java后端

,

请参考下面的代码,这对我有用..

将以下代码粘贴到前端,即 React (app.js)

    import React,{useState,useEffect} from "react"
import Axios from 'axios'
import './App.css';



function App() {
const [frommail,setfrommail]=useState("")
const [password,setpassword]=useState(0)
const [tomail,settomail]=useState("")

useEffect(()=>{
  Axios.get("http://localhost:3001/read").then((response)=>{
    console.log(response.data)
  })
},[])


const sendmail=()=>{
  Axios.post("http://localhost:3001/mail",{frommail:frommail,password:password,tomail:tomail}).then((response)=>{
    if (response.data.msg === 'success'){
        alert("Email sent,awesome!"); 
   
    }else if(response.data.msg === 'fail'){
        alert("Oops,something went wrong. Try again")
    }
})

}


  return (
    <div className="App">
     
      <label>From</label>
      <input type="text" onChange={(e)=>{setfrommail(e.target.value)}}/>
      <label>From Mail Password</label>
      <input type="text" onChange={(e)=>{setpassword(e.target.value)}}/>
      <label>To address</label>
      <input type="text" onChange={(e)=>{settomail(e.target.value)}}/>
      <input type="submit" onClick={sendmail}/>

    </div>
  );
}

export default App;

然后这里是后端的代码,即 Node js

const express = require("express");

const app = express();
const cors=require('cors')
var nodemailer = require('nodemailer');



app.use(express.json());
app.use(cors())



app.post(("/mail"),async (req,res)=>{
  const frommail=req.body.frommail
  const password = req.body.password
  const tomail=req.body.tomail
  var transporter = nodemailer.createTransport({
    service: 'gmail',auth: {
      user: frommail,pass: password
    }
  });
  
  var mailOptions = {
    from: frommail,to: tomail,subject: 'Sending Email using Node.js',text: `sending mail using Node.js was running successfully. Hope it help you. For more code and project Please Refer my github page`
    // html: '<h1>Hi Smartherd</h1><p>Your Messsage</p>'        
  };
  
  transporter.sendMail(mailOptions,function(error,info){
    if (error) {
      res.json({
        msg: 'fail'
      });
    } 
    else{
      res.json({
        msg: 'success'
      })
    }
  });

})

app.listen(3001,() => {
  console.log("Server is Running");
});

最后确保您的发件人邮件 ID 的应用访问安全性较低:

check this feature is enable in your gmail account