Прикрепление Azure Blob из потока к электронной почте SendGrid - PullRequest
0 голосов
/ 28 апреля 2020

Я пытаюсь отправить BLOB-объект Azure в виде вложения через SendGrid. Мой первый шаг - загрузить блоб следующим образом:

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?

Я также нашел эту статью в стеке, более или менее похожую на вопрос, но не в python, и на которую нет прямого ответа. Этот вопрос здесь

1 Ответ

0 голосов
/ 01 мая 2020

Под 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)
...