100daysofweb-with-python-course icon indicating copy to clipboard operation
100daysofweb-with-python-course copied to clipboard

Days 65-68 Heroku - Sendgrid changes

Open shutteritch opened this issue 5 years ago • 4 comments

Hello!

I had two errors when trying to send email with sendgrid.

The first seemed to relate to the order of the variables in which I had to change from: mail = Mail(from_email, subject, to_email, content) to: mail = Mail(from_email, to_email, subject, content)

And then the second referred to the response which I had to change from: response = sg.client.mail.send.post(request_body=mail.get()) to: response = sg.send(mail)

I also discovered that I didn't need to import Email & Content so the following worked for me:

import sendgrid
from sendgrid.helpers.mail import Mail

sg = sendgrid.SendGridAPIClient(api_key="MY_API_KEY")

from_email = "[email protected]"
subject = "Winter is coming"
to_email = "[email protected]"
content = "Hey Iain, This works much better"

mail = Mail(from_email, to_email, subject, content)

response = sg.send(mail)

print(response.status_code)
print(response.body)
print(response.headers)

shutteritch avatar Jun 04 '20 21:06 shutteritch

Here's the sendgrid docs that I ended up looking at: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/send_a_single_email_to_a_single_recipient.md

shutteritch avatar Jun 04 '20 21:06 shutteritch

Thanks @shutteritch I will look tomorrow.

bbelderbos avatar Jun 04 '20 22:06 bbelderbos

Ah seems @hobojoe1848's lesson actually. I see he pinned it to sendgrid==5.6.0, are you using that version or 6.x?

We upgraded back in December on the platform and struggled with some breaking changes in 6.1.0.

Looking at our changes then:

-sendgrid==5.6.0
+sendgrid==6.1.0
...
-sg = sendgrid.SendGridAPIClient(apikey=config('SENDGRID_API_KEY'))
+sg = sendgrid.SendGridAPIClient(api_key=config('SENDGRID_API_KEY'))
...
-    mail = Mail(from_email, subject, to_email, content)
+    mail = Mail(from_email, to_email, subject, content)
...
+    message = Mail(
+        from_email=from_email,
+        to_emails=to_email,
+        subject=subject,
+        plain_text_content=body if not html else None,
+        html_content=body if html else None
+    )
...
+    response = sg.send(message) 
(before)
sg.client.mail.send.post(request_body=mail.get())

So yeah I think it would be useful to include a script for sendgrid 6.x as that is the default now.

bbelderbos avatar Jun 08 '20 07:06 bbelderbos

@shutteritch we can include one, but as you seem to have one ready, you could also contribute by opening a PR against this repo. Thanks

bbelderbos avatar Jun 08 '20 07:06 bbelderbos

Seems this was fixed via PR.

bbelderbos avatar Feb 09 '24 16:02 bbelderbos