4
votes

I'm trying to use sendgrid to send email from my Python application.

It's sending fine using the mail helper and the following syntax:

sgmessage = mail.Mail(from_email, message.subject, to_email, content)
sg.client.mail.send.post(request_body=sgmessage.get())

But I can't find the way to send an email which has a multipart/alternative content type with text & html versions?

I've tried things like this:

sgmessage = mail.Mail(from_email, message.subject, to_email)
sgmessage.add_content(content)
sgmessage.add_content(htmlcontent)

But that gives me Bad Request when I try to send.

Could someone point me to the documentation or other tip for achieving this?

Also attachments -- I can't find docs for that handy mail helper which would help me add attachments ability to my code.

3

3 Answers

9
votes

Mail Helper Source https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/helpers/mail/mail.py

mail_html = Content(type_='text/html', value='<h1>Test Mail</h1><p>This is a test email message.</p>')
mail_txt = Content(type_='text/plain', value='This is a test email message.')
mail = Mail(mail_from, mail_subject, mail_to, mail_html)
mail.add_content(mail_txt)
response = sg.client.mail.send.post(request_body=mail.get())

The sample links are still 404's.

0
votes

Have you looked at the SendGrid Python Library? The basic example only shows one content type, but the "kitchen sink" example shows setting both contents.

0
votes
import os

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail


def send_email(emails, notification_text, subject):
    """Send Emails

    Send email to the mail ids

    :param emails: emails of the user
    :type emails: list
    :param notification_text: notification text
    :type notification_text: str
    :param request_link: link to the requet
    :type request_link: str
    :param subject: subject of the email
    :type subject: str

    :rtype: str
    """
    html_content = '<strong>' + notification_text + '</strong>'
    emails = emails
    message = Mail(
        from_email='yourSendGridVerifiedEmail',
        to_emails=emails,
        subject=subject,
        html_content=html_content)
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        sg.send(message)
        return "Email Sent"
    except Exception as e:
        return e.message