使用React.js+Express.js发送电子邮件

Send an Email Using React.js + Express.js

本文关键字:电子邮件 js React js+Express 使用      更新时间:2023-09-26

我在ES6中使用React.js构建了一个web应用程序。我目前想创建一个基本的"联系我们"页面,并想发送一封电子邮件。我是React的新手,刚刚发现我实际上无法使用React本身发送电子邮件。我正在学习nodemailerexpress-mailer的教程,但在将示例代码与React文件集成时遇到了一些困难。具体来说,调用node expressFile.js是可行的,但我不知道如何将其链接到我的React前端。

Nodemailer:https://github.com/nodemailer/nodemailer

快递员:https://www.npmjs.com/package/express-mailer

我的表单React组件如下。我该如何编写一个Express文件,以便从我的React组件中的contactUs()方法调用它?谢谢

import React from 'react';
import {
  Col,
  Input,
  Button,
Jumbotron
} from 'react-bootstrap';
class ContactView extends React.Component{
  contactUs() {
    // TODO: Send the email here
  }
  render(){
    return (
      <div>
    <Input type="email" ref="contact_email" placeholder="Your email address"/>
    <Input type="text" ref="contact_subject" placeholder="Subject"/>
    <Input type="textarea" ref="contact_content" placeholder="Content"/>
    <Button onClick={this.contactUs.bind(this)} bsStyle="primary" bsSize="large">Submit</Button>
  </div>
)
  }
};
export default ContactView;

单击按钮后,执行一个到express服务器的ajax POST请求,即"/contactus"/contactus可以从邮件数据中提取电子邮件、主题和内容,并发送到邮件功能。

反应中:

$.ajax({
    url: '/contactus',
    dataType: 'json',
    cache: false,
    success: function(data) {
        // Success..
    }.bind(this),
    error: function(xhr, status, err) {
        console.error(status, err.toString());
    }.bind(this)
});

在express中,在express post处理程序中添加nodemailer代码:

app.post('/contactus', function (req, res) {
    // node mailer code
});

@ryan jenkin是完全正确的。

或者,如果您不希望jQuery作为依赖项,则可以使用本机fetchapi。此外,我通常会设置表单,使每个输入都有一个状态,然后在字符串化的blob中使用该状态。

客户端(React):

handleSubmit(e){
  e.preventDefault()
  fetch('/contactus', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: this.state.email,
      // then continue this with the other inputs, such as email body, etc.
    })
  })
  .then((response) => response.json())
  .then((responseJson) => {
    if (responseJson.success) {
      this.setState({formSent: true})
    }
    else this.setState({formSent: false})
  })
  .catch((error) => {
    console.error(error);
  });
}
render(){
  return (
    <form onSubmit={this.handleSubmit} >
      <input type="text" name="email" value={this.state.email} />
      // continue this with other inputs, like name etc
    </form>
  )
}