我正在尝试通过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却找不到类似的东西。 SendGrid GitHub
有人知道如何使用Python进行此操作吗?
我还在Stack上发现了这篇文章,该文章或多或少是相同的问题,但不是在python中,也没有直接回答。This question here
sendgrid.helpers.mail
下有一个附件模块,您可以在这里参考:Attachment。下面是我的测试代码,也许您可以尝试一下。
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='[email protected]',
to_emails='[email protected]',
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)