Skip to content

fix: serialize From objects passed to Personalization.add_email - #1138

Open
emailshelp wants to merge 2 commits into
sendgrid:mainfrom
emailshelp:patch-1
Open

emailshelp wants to merge 2 commits into
sendgrid:mainfrom
emailshelp:patch-1

Conversation

@emailshelp

Copy link
Copy Markdown

There is no issue for this (issues are disabled), so the details are here.

Personalization.add_email() accepts a From but stores the object itself, while set_from() stores From.get(). The object then reaches the request body and send() fails before any HTTP call:

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Personalization, From, To

m = Mail(from_email="default@example.org", subject="Hi", plain_text_content="Body")
p = Personalization()
p.add_to(To("to@example.com"))
p.add_email(From("billing@example.org", "Billing"))
m.add_personalization(p)
SendGridAPIClient("SG.x").send(m)
# TypeError: Object of type From is not JSON serializable

Checked against sendgrid==6.12.5 from PyPI with only the HTTP transport mocked: add_email(From(...)) raises the TypeError with 0 transport calls; set_from(From(...)) makes 1 call with "from": {"name": "Billing", "email": "billing@example.org"} in the personalization. Per-personalization from is documented in the Mail Send API, so this is a supported use.

Fix: add_email delegates From to set_from, the same way it delegates To/Cc/Bcc to add_to/add_cc/add_bcc.

Test: test_personalization_add_email_from_serializes_like_set_from checks that both methods produce the same get() output and that it is JSON-serializable. It fails on main and passes with the fix; the full test/unit suite passes locally (110 tests, Python 3.13).

Checklist

  • I acknowledge that all my contributions will be made under the project's license
  • I have made a material change to the repo (functionality, testing, spelling, grammar)
  • I have read the Contribution Guidelines and my PR follows them
  • I have titled the PR appropriately
  • I have updated my branch with the main branch
  • I have added tests that prove my fix is effective or that my feature works
  • I have added the necessary documentation about the functionality in the appropriate .md file (no behaviour change for documented use)
  • I have added inline documentation to the code I modified (one-line change)

— Emails.help (https://emails.help)

add_email stored the From object itself, so send() failed with "Object of type From is not JSON serializable". Use set_from, which stores the API dict.
Fails on main: get()['from'] is the From object rather than a dict.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant