简体   繁体   中英

Sending email with firebase, sendgrid, angular

I've tried to configure emailfunctionalities with firebase/sendgrid a my Angular-app. Function is called when hitting a button

**--INDEX.JS**  
const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const SENDGRID_API_KEY = functions.config().sendgrid.key

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);


exports.httpEmail = functions.https.onRequest((req, res) =>
{

  cors(req, res, () =>
  {

    const toName = req.body.toName;
    const toEmail = req.body.toEmail;

    const msg = {
      to: toEmail,
      from: 'hello@angularfirebase.com',
      subject: 'New Follower',
      // text: `Hey ${toName}. You have a new follower!!! `,
      // html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,

      // custom templates
      templateId: '300e1045-5b30-4f15-8c43-41754b73fe4f',
      substitutionWrappers: ['{{', '}}'],
      substitutions: {
        name: toName
        // and other custom properties here
      }
    };

    return sgMail.send(msg)

      .then(() => res.status(200).send('email sent!'))
      .catch(err => res.status(400).send(err))

  });

});


**--SendEmailComponent**
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { RequestOptions } from 'http';

@Component({
  selector: 'app-send-email',
  templateUrl: './send-email.component.html',
  styleUrls: ['./send-email.component.css']
})
export class SendEmailComponent implements OnInit
{
  //fields
  endpoint = 'https://**blankblank**.cloudfunctions.net/httpEmail';
  httpOptions =
    {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      })
    }

  //ctr
  constructor(private http: HttpClient) { }

  //lifehook
  ngOnInit()
  {
  }

  //methods
  sendEmail()
  {
    const data =
      {
        toEmail: 'someone@something.net',
        toName: 'Some One'
      }

    //post
    this.http.post(this.endpoint, data, this.httpOptions).subscribe(data => console.log('email sent: ', data));
  }

}

I tried different tutorials , but I always get this error:

Failed to load https:// blankblank .cloudfunctions.net/httpEmail: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

You need to include dummy values for the text and html attributes for SendGrid. Also this is how the Cors method should look that I was able to get working

index.js:

const cors = require('cors')({ origin: true });
const sendGrid = require('@sendgrid/mail');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
sendGrid.setApiKey(functions.config().sendgrid.apikey);
sendGrid.setSubstitutionWrappers('{{', '}}');

exports.sendBookingEmail = functions.https.onRequest((req, res) => {

    cors(req,res, () => {

const message = {
  to: req.body.email,
  bcc: ['test@email.com'],
  from: 'test@email.com',
  text: 'email',
  html: '<strong>email</strong>',      
  substitutions: {
    contactName: 'test name',
    siteName: 'test site'
  }
} 

        sendGrid.send(message);
        res.status(200).send('email sent new');
    }); 

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM