Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sendgrid add CC to email

I am using SendGrid for Python. I want to CC some people in an email. It seems like they may no longer support CC'ing on emails, though I'm not positive if that's true? But surely there is a work around to it somehow, but I am surprised I can't find much support on this.

Here is my basic code:

sg = sendgrid.SendGridAPIClient(apikey='*****')
from_email = Email(sender_address, sender_name)
to_email = Email(email_address)
subject = subject
content = Content("text/plain", email_message)
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())

How can I modify this so it will CC someone on an email?

like image 569
Emac Avatar asked Jul 11 '26 12:07

Emac


2 Answers

Using the SendGrid's Personalization() or Email() class did not work for me. This is how I got it to work:

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

# using a list of tuples for emails
# e.g. [('[email protected]', '[email protected]'),('[email protected]', '[email protected]')]
to_emails = []
for r in recipients:
  to_emails.append((r, r))

# note the Cc class
cc_emails = []
for c in cc:
  cc_emails.append(Cc(c, c))

message = Mail(
  from_email=from_email,
  to_emails=to_emails,
  subject='My Subject',
  html_content=f'<div>My HTML Email...</div>'
)

if cc_emails:
  message.add_cc(cc_emails)

try:
  sg = SendGridAPIClient(os.getenv('SENDGRID_API_KEY'))            
  sg.send(message)  
except Exception as e:            
  print(f'{e}')

Hopefully this helps someone.

like image 77
hugo Avatar answered Jul 14 '26 00:07

hugo


I resolved it. Santiago's answer got me mostly there, but here is what I needed to do:

sg = sendgrid.SendGridAPIClient(apikey='****')
from_email = Email(sender_address, sender_name)
to_email = Email(to_email)
cc_email = Email(cc_email)
p = Personalization()
p.add_to(to_email)
p.add_cc(cc_email)
subject = subject
content = Content("text/plain", email_message)
mail = Mail(from_email, subject, to_email, content)
mail.add_personalization(p)
response = sg.client.mail.send.post(request_body=mail.get())

If you don't include the p.add_to(to_email) it rejects it because there is no "to email" in the personalization object. Also, if you don't include the "to_email" inside the mail object it rejects it because it is looking for that argument, so you have to be a bit redundant and define it twice.

like image 44
Emac Avatar answered Jul 14 '26 01:07

Emac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!