I'm attempting to send an Azure Blob as an attachment via SendGrid. My first step is to download the blob as such:
download_client=BlobClient.from_connection_string(
conn_str=az_str,
container_name=container_name,
blob_name=blob_name)
download_stream = download_client.download_blob()
I have found that SendGrid has the functionality to add files from memory with NodeJS, however I did not find anything like that with Python. SendGrid GitHub
Does anyone know how to do this with Python?
I also found this article on Stack that is more-or-less the same question but not in python and not answered directly. This question here
There is an attachment module under the sendgrid.helpers.mail
, you could refer to here: Attachment . Below is my test code, maybe you could have a try.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.