Sendgrid 的 QueueTrigger 绑定 -Python

QueueTrigger Bindings for Sendgrid -Python

受此指导 post 我编写了以下队列触发代码,用于在消息排队时发送电子邮件。

import logging
import sendgrid
import azure.functions as func
import os
def main(msg: func.QueueMessage) -> None:
    logging.info('Python queue trigger function processed a queue item: %s',
                 msg.get_body().decode('utf-8'))
    
   
    data = {
        "personalizations": [
          {
            "to": [
              {
                "email": "rrrrrrrr"
              }
            ],
            "subject": "Sending with SendGrid is Fun"
          }
        ],
        "from": {
          "email": "ghyu"
        },
        "content": [
          {
            "type": "text/plain",
            "value": "and easy to do anywhere, even with Python"
          }
         ]
    }
    print('Sending email using SendGrid:', data)
    with open(os.environ[_AZURE_FUNCTION_SENDGRID_OUTPUT_ENV_NAME], 'wb') as f:
      json.dump(data,f)

function.json

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "msg",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "outqueue1",
      "connection": "storageaccountautom92bb_STORAGE"
    },
    
    {
      
      "name": "outputMessage",
      "type": "sendGrid",
      "from": "ghyu",
      "apiKey": "MY_SENDGRID_API_KEY",
      "direction": "out"
    }
  ],
  "disabled": false
}

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "hjk",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "storageaccountautom92bb_STORAGE": "hjk",
    "MY_SENDGRID_API_KEY": "tyhuE",
    "_AZURE_FUNCTION_SENDGRID_OUTPUT_ENV_NAME" : "GIS klop",
    "_AZURE_FUNCTION_QUEUE_INPUT_ENV_NAME" : "msg"
  }
}

虽然该函数会在消息排队时对其进行响应,但它无法发送电子邮件。它抛出一个错误;

the following parameters are declared in function.json but not in Python: {'outputMessage'}
  1. 我怎样才能最好地解决这个问题?
  2. 外绑定正确吗?

Azure Function禁止了发送邮件的端口,所以我们必须使用sendgrid来发送邮件。(这是一个第三方工具,但是已经集成到azure functions binding中,所以我们可以直接使用。)

例如,如果您要将电子邮件从电子邮件 A 发送到电子邮件 B。

首先,转到sendgrid website,创建发​​件人并验证电子邮件A:

之后,邮箱A就可以通过sendgrid发送邮件了。

现在我们需要生成一个SendGrid API键并复制并存储API键:(这将作为环境变量填写在local.settings.json的Values部分以阅读。)

然后,您就可以用它来发送电子邮件了:

host.json

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 3.1.0)"
  }
}

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "SendGrid_API_Key": "SG._-yYnhzER2SEbAvzOxSHnA.xxxxxx",
    "0730bowmanwindow_STORAGE": "DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net"
  }
}

function.json

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "msg",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "myqueue",
      "connection": "0730bowmanwindow_STORAGE"
    },
    {
      "type": "sendGrid",
      "name": "sendGridMessage",
      "direction": "out",
      "apiKey": "SendGrid_API_Key",
      "from": "emailA@emailA.com"
    }
  ]
}

__init__.py

import logging
import json
import azure.functions as func


def main(msg: func.QueueMessage, sendGridMessage: func.Out[str]) -> None:
    logging.info('Python queue trigger function processed a queue item: %s',
                 msg.get_body().decode('utf-8'))
    value = "Sent from Azure Functions"

    message = {
        "personalizations": [ {
          "to": [{
            "email": "emailB@emailB.com"
            }]}],
        "subject": "Azure Functions email with SendGrid",
        "content": [{
            "type": "text/plain",
            "value": value }]
    }
    sendGridMessage.set(json.dumps(message))

之后,我给'myqueue'发了一条消息,emailB收到了邮件:

对了,这只能保证投递成功,因为有些邮箱拒绝接受通过sendgrid发送的邮件。这种情况下还是会得到200响应,但是收件人收不到邮件。(这种情况收件人需要去邮箱设置解除相关限制。)