Cloud Functions 函数任务处理程序

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

使用 Cloud Tasks 来触发 Cloud Functions 函数。





如需了解如何安装和使用 Cloud Tasks 客户端库,请参阅 Cloud Tasks 客户端库

const sendgrid = require('@sendgrid/mail');

 * Responds to an HTTP request from Cloud Tasks and sends an email using data
 * from the request body.
 * @param {object} req Cloud Function request context.
 * @param {object} req.body The request payload.
 * @param {string} req.body.to_email Email address of the recipient.
 * @param {string} req.body.to_name Name of the recipient.
 * @param {string} req.body.from_name Name of the sender.
 * @param {object} res Cloud Function response context.
exports.sendEmail = async (req, res) => {
  // Get the SendGrid API key from the environment variable.
  const key = process.env.SENDGRID_API_KEY;
  if (!key) {
    const error = new Error(
      'SENDGRID_API_KEY was not provided as environment variable.'
    error.code = 401;
    throw error;

  // Get the body from the Cloud Task request.
  const {to_email, to_name, from_name} = req.body;
  if (!to_email) {
    const error = new Error('Email address not provided.');
    error.code = 400;
    throw error;
  } else if (!to_name) {
    const error = new Error('Recipient name not provided.');
    error.code = 400;
    throw error;
  } else if (!from_name) {
    const error = new Error('Sender name not provided.');
    error.code = 400;
    throw error;

  // Construct the email request.
  const msg = {
    to: to_email,
    from: '',
    subject: 'A Postcard Just for You!',
    html: postcardHTML(to_name, from_name),

  try {
    await sendgrid.send(msg);
    // Send OK to Cloud Task queue to delete task.
    res.status(200).send('Postcard Sent!');
  } catch (error) {
    // Any status code other than 2xx or 503 will trigger the task to retry.


如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器