在这些例子之后,我正在尝试使用谷歌云函数发送电子邮件:https://github.com/firebase/functions-samples/tree/master/quickstarts/email-users和 https://angularfirebase.com/lessons/sendgrid-v3-nodejs-transactional-email-cloud-function/然后我不得不做一些调整以适应发展中的技术,我的结果是这样的:
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const sendGrid = require('@sendgrid/mail');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
const SENDGRID_API_KEY="***";
sgMail.setApiKey(SENDGRID_API_KEY);
sendGrid.setApiKey(functions.config().sendgrid.apikey);
sendGrid.setSubstitutionWrappers('{{', '}}');
exports.httpEmail = functions.https.onRequest((req, res) => {
cors( req, res, () => {
const name = req.body.toName;
const email = req.body.Email;
const id = req.body.ID;
const msg = {
to: email,
from: mail@homepage.com',
subject: id,
text: `Hello {{name}}`,
html: `<h1>Hello {{name}}</h1>`
};
return sgMail.send(msg)
.then(() => res.status(200).send('email sent!') )
.catch(err => res.status(400).send(err) )
});});
现在这给了我一个语法错误
/user_code/index.js:20 to: {{email}}, ^ 语法错误:意外的标记
{
"name": "email",
"description": "sending emails",
"version": "0.0.1",
"dependencies": {
"sendgrid/mail": "^6.3.1",
"cors": "^2.8.1",
"moment": "^2.17.1",
"firebase-admin": "~5.11.0",
"firebase-functions": "^1.0.0"
},
"scripts": {
"lint": "./node_modules/.bin/eslint --max-warnings=0 .",
"serve": "firebase serve --only functions",
"shell": "firebase experimental:functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"private": true
}
这给了我一个解析错误:
无法解析 package.json,第 7 行第 6 列出错
这两个错误对我来说都没有意义,我不得不进行 4 种不同的调整,这让我怀疑我是否走在正确的道路上。有人有一个工作示例或教程,包括cors,带有变量的文本和sendgrid?或者有人可以为我解决错误消息吗?
- 第一个错误是由于
mail@homepage'
中没有开场白 - 其次可能是
sendgrid/mail
之前没有"@",或者"dependencies"
下没有缩进
虽然sendgrid
是一个不错的选择,但您也可以查看 nodemailer
.它不需要 API 密钥。这两种方法的工作方式相同,如以下示例所示。
app.yaml
runtime: nodejs8
包.json
{
"dependencies": {
"nodemailer": "^4.0.1",
"@sendgrid/mail": "^6.3.1"
}
}
应用.js
const nodemailer = require('nodemailer');
const sendgridmail = require('@sendgrid/mail');
exports.sendEmail = (req, res) => {
// destination email passed as argument
var email = req.query.message;
// sender email config (mailserver)
var gmailEmail = process.env.EMAIL;
var gmailPassword = process.env.PASSWORD;
// Nodemailer config
var mailTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: gmailEmail,
pass: gmailPassword
}
});
var msg = {
from: gmailEmail,
to: email,
subject: 'Nodemailer',
text: 'Sent with Nodemailer'
};
mailTransport.sendMail(msg);
// Sendgrid config
sendgridmail.setApiKey(process.env.GRIDKEY);
var msg = {
from: gmailEmail,
to: email,
subject: 'Sendgrid',
text: 'Sent with Sendgrid/mail'
};
sendgridmail.send(msg);
return `Sent two emails with Sendgrid and Nodemailer`;
};
注意:由于我使用Gmail作为邮件服务器,因此需要两个额外的步骤才能从中发送电子邮件:
- 允许安全性较低的应用
- 允许访问您的谷歌帐户