4

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 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Look at this link . At the time of writing, you need to look at the line of 31, in the type method.
Here's the link I got while I'm not logged in, so should hopefully stay good: github.com/sendgrid/sendgrid-python/blob/master/examples/…
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.