如何使用sendgrid使用ReactJS和firebase发送电子邮件?

时间:2018-02-26 06:30:24

标签: reactjs sendgrid

我已经制作了contactform组件,我正在使用sendgrid和firebase。我已经安装了sendgrid和firebase,我将数据推送到firebase,数据必须显示在sendgrid的电子邮件中。

import React, { Component } from 'react';
import firebase from 'firebase';
import sgMail from '@sendgrid/mail';

const config = {
    apiKey: process.env.REACT_APP_FIREBASE_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
    databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
    projectId: process.env.REACT_APP_PROJECT_ID,
    storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_SENDER_ID
    };
    firebase.initializeApp(config);

    //Reference content from collection 
    let contentref = firebase.database().ref('content');

  //SendGrid Email
  //const sgMail = require('@sendgrid/mail');
  sgMail.setApiKey(process.env.REACT_APP_SENDGRID_API_KEY);

class ContactForm extends Component {

render() {

    return <div> (
 const msg = {
    to: 'myemail@gmail.com',
    from: 'test@example.com',
    subject: 'Sending with SendGrid is Fun',
    text: 'and easy to do anywhere, even with Node.js',
    html: '<strong>and easy to do anywhere, even with Node.js</strong>',
  };
  sgMail.send(msg);

 </div>);
  }
}

export default ContactForm;

我没有收到myemail@gmail.com的电子邮件,为什么会这样?

1 个答案:

答案 0 :(得分:0)

您必须遵循Sendgrid建议并使用server-based application

Making your API key publicly accessible could result in anyone authenticating API calls with your API key — this is a significant security concern both for you and SendGrid.

  • 创建一个使用已构建应用程序的Express服务器,并为email sender service添加路由。
app.post('/email', (req, res) => sendEmail(req.body, res))
  • 在React应用程序中,您可以使用Axios来调用您的路线。
import axios from 'axios';

export const sendEmail = async (data) => axios({
  method: 'post',
  url: '/email',
  data
})
  • 按照他们的文档和您的需求构建Sendgrid电子邮件,例如:
  {
    personalizations: [
      {
        to: [
          {
            email: 'some@email.com',
            name: 'Someone',
          },
        ],
        subject: 'test',
      },
    ],
    from: {
      email: 'who@sent.com',
      name: 'who sent',
    },
    reply_to: {
      email: 'email@to.com',
      name: 'reply',
    },
    content: [
      {
        type: 'text/html',
        value: 'HELLO WORLD',
      },
    ],
  }
  • 从以前在组件中调用axios函数:
const sendRequestDemoEmail = async (emailMessage) => {
  return await sendEmail(emailMessage)
}