首页 > 解决方案 > 将 Azure Blob 从流附加到 SendGrid 电子邮件

问题描述

我正在尝试通过 SendGrid 将 Azure Blob 作为附件发送。我的第一步是像这样下载 blob:

download_client=BlobClient.from_connection_string(
        conn_str=az_str, 
        container_name=container_name, 
        blob_name=blob_name) 

download_stream = download_client.download_blob()

我发现 SendGrid 具有使用 NodeJS 从内存中添加文件的功能,但是我没有在 Python 中找到类似的东西。发送网格 GitHub

有谁知道如何用 Python 做到这一点?

我还在 Stack 上发现这篇文章或多或少是相同的问题,但不是在 python 中,也没有直接回答。 这个问题在这里

标签: pythonazureazure-blob-storagesendgrid

解决方案


下有一个附件模块sendgrid.helpers.mail,您可以参考这里:附件。下面是我的测试代码,也许你可以试一试。

import sendgrid
import os
from sendgrid.helpers.mail import *
import base64
from sendgrid import SendGridAPIClient
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
from io import BytesIO

message = Mail(
    from_email='from_email@example.com',
    to_emails='to@example.com',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')

connect_str ='storage connection string'
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
blobclient=blob_service_client.get_blob_client(container='test',blob='nodejschinesedoc.pdf')
streamdownloader =blobclient.download_blob()
stream = BytesIO()
streamdownloader.download_to_stream(stream)


encoded = base64.b64encode(stream.getvalue()).decode()
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType('application/pdf')
attachment.file_name = FileName('test_filename.pdf')
attachment.disposition = Disposition('attachment')
attachment.content_id = ContentId('Example Content ID')
message.attachment = attachment
try:
    sendgrid_client = SendGridAPIClient('sendgrid API key')
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.args)

推荐阅读