Valeria, parte de este gran equipo, nos hizo el favor de crear este enunciado porque conoce muy bien dicho tema.
Solución:
Encontré una solución. Reemplacé esta línea:
pdf = open(pdf_path, "rb").read().encode("base64")
Por esto :
with open(pdf_path, 'rb') as f:
data = f.read()
encoded = base64.b64encode(data)
Ahora funciona. Puedo enviar un archivo codificado en set_content:
attachment.set_content(encoded)
Nota: La respuesta anterior funciona para Sendgrid v2 o inferior. Para v3 y uso superior:
encoded = base64.b64encode(data).decode()
Esta es mi solución, funciona con Sendgrid V3
# Where it was uploaded Path.
file_path = "MY_FILE_PATH"
with open(file_path, 'rb') as f:
data = f.read()
# Encode contents of file as Base 64
encoded = base64.b64encode(data).decode()
"""Build attachment"""
attachment = Attachment()
attachment.content = encoded
attachment.type = "application/pdf"
attachment.filename = "my_pdf_attachment.pdf"
attachment.disposition = "attachment"
attachment.content_id = "PDF Document file"
sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
from_email = Email("[email protected]")
to_email = Email('[email protected]')
content = Content("text/html", html_content)
mail = Mail(from_email, 'Attachment mail PDF', to_email, content)
mail.add_attachment(attachment)
try:
response = sg.client.mail.send.post(request_body=mail.get())
except urllib.HTTPError as e:
print(e.read())
exit()
Directamente de los documentos de Sendgrid:
import urllib.request as urllib
import base64
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition, ContentId)
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
message = Mail(
from_email='[email protected]',
to_emails='[email protected]',
subject='Sending with Twilio SendGrid is Fun',
html_content='and easy to do anywhere, even with Python')
file_path = 'example.pdf'
with open(file_path, 'rb') as f:
data = f.read()
f.close()
encoded = base64.b64encode(data).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(os.environ.get('SENDGRID_API_KEY'))
response = sendgrid_client.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)
Te mostramos las reseñas y valoraciones de los lectores
Nos encantaría que puedieras recomendar este tutorial si te fue útil.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)