使用Gmail API代表客户发送电子邮件?

时间:2018-04-02 11:56:53

标签: reactjs firebase firebase-authentication authorization gmail-api

所以我使用了在reactjs应用程序中实现了Google登录 火力。

我在主页上添加了一个表单,用户在登录后直接登陆。我希望用户使用他的(用户)Gmail将表单数据发送给特定的供应商。我知道我必须使用不同的范围(即https://www.googleapis.com/auth/gmail.send)代表用户发送电子邮件以进行授权。此外,只有在第一次发送数据时才会询问权限。

我不明白我怎么能用反应来实现呢?我已经用谷歌检查过,找不到任何有用的东西。如果有任何链接或文档可以帮助我,请告诉我。

以下是代码。

index.js

import firebase from 'firebase'

var config = {
    apiKey: "yourapikey",
    authDomain: "yourdomain.firebaseapp.com",
    databaseURL: "yourdatabase.firebaseio.com"
}

firebase.initializeApp(config);

app.js

import React, { Component } from 'react';
import firebase from 'firebase'
import Header from './components/header'

class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      user: null
    }
    this.handleAuth = this.handleAuth.bind(this)
    this.handleLogout = this.handleLogout.bind(this)
  }

  componentWillMount () {
    firebase.auth().onAuthStateChanged(user => {
      this.setState({ user })
    })
  }

  handleAuth () {
    const provider = new firebase.auth.GoogleAuthProvider()
    provider.addScope('https://www.googleapis.com/auth/plus.login')

    firebase.auth().signInWithPopup(provider)
      .then(result => console.log(`${result.user.email} User signed in`))
      .catch(error => console.log(`Error ${error.code}: ${error.message}`))
  }

  handleLogout () {
    firebase.auth().signOut()
      .then(result => console.log('user signed out'))
      .catch(error => console.log(`Error ${error.code}: ${error.message}`))
  }

  render() {
    return (
      <div>
        <Header
          appName='Chat Real'
          user={this.state.user}
          onAuth={this.handleAuth}
          onLogout={this.handleLogout}
        />
      </div>
    );
  }
}

export default App;

header.js

import React from 'react'

const Header = ({ appName, user, onAuth, onLogout }) => {

  function renderUserData () {
    return (
        <div>
            <ul className='navbar right'>
                <li>
                <img
                    width='32'
                    className='avatar circle responsive-img'
                    src={user.photoURL}
                />
                </li>
                <li>{user.displayName}</li>
                <li>
                <button
                    className='waves-effect waves-light btn blue darken-1'
                    onClick={onLogout}
                >
                    Logout
                </button>
                </li>
            </ul>
            <form onSubmit={(e) => this.handleSubmit(e)}>
                <label>Title</label><br/>
                <input type="text" name="title" /><br/>
                <label>Body</label><br/>
                <input type="text" name="body" /><br/>
                <input type="submit" />
            </form>
        </div>
    )
  }

  function renderLoginButton () {
    return (
      <ul className='right'>
        <li>
          <button
            className='waves-effect waves-light btn blue darken-1'
            onClick={onAuth}
          >
            Login
          </button>
        </li>
      </ul>
    )
  }

  return (
    <nav className='blue darken-4'>
      <div className='nav-wrapper container'>
        <a href='#' className='left brand-logo'>{appName}</a>
        {user ? renderUserData() : renderLoginButton()}
      </div>
    </nav>
  )
}

export default Header

1 个答案:

答案 0 :(得分:1)

对您的应用进行以下更改。

  1. 首先,您要求用户在handleAuth文件的app.js函数中发送邮件的权限。参考scope
  2. handleAuth () {
        const provider = new firebase.auth.GoogleAuthProvider()
        provider.addScope('https://www.googleapis.com/auth/plus.login')
        provider.addScope('https://www.googleapis.com/auth/gmail.send')
    
        firebase.auth().signInWithPopup(provider)
            .then(result => console.log(`${result.user.email} User signed in`))
            .catch(error => console.log(`Error ${error.code}: ${error.message}`))
    }

    1. 更改firebase auth的令牌管理,以从 Google登录收到的OAuth2获取访问令牌。您可以refer代码 -
    2. firebase.auth().signInWithPopup(provider).then(function(result) {
              // This gives you a Google Access Token. You can use it to access the Google API.
              var token = result.credential.accessToken;
              // The signed-in user info.
              var user = result.user;
              // ...
              }).catch(function(error) {
              // Handle Errors here.
              var errorCode = error.code;
              var errorMessage = error.message;
              // The email of the user's account used.
              var email = error.email;
              // The firebase.auth.AuthCredential type that was used.
              var credential = error.credential;
              // ...
      });

      1. 一旦您从用户的登录中获得令牌,您就可以使用相同的方式通过GMail API发送邮件。 API根据您的使用情况支持nodejs和javascript。
      2. 希望这会有所帮助