python - 将 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 中,也没有直接回答。 这个问题在这里
解决方案
下有一个附件模块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)
推荐阅读
- sapui5 - 什么是部件:和路径:在 sapui5 中,为什么要使用它们?
- c# - Nuget包安装报错:Install-Package Google.Apis.Drive.v3
- ruby-on-rails - 如何通过 ActiveMerhant StripeGateway 获取客户 ID -(Ruby on Rails)
- c# - 从数据库中获取下拉列表选择的值
- sql-server - 在 SQL Server 上报告以前的记录
- react-native - 如何在 ReactNative 中访问另一个控件中的一个控件属性
- node.js - 如何使用 npm run build 修复此错误?
- docker - 使用 docker 映像部署时,容器的 Web 应用程序仅显示默认页面
- java - 在Java中计算文本文件中字符的出现次数
- arrays - 使用python对每条线的交叉点进行分组