sendgrid / sendgrid-python

The Official Twilio SendGrid Python API Library
https://sendgrid.com
MIT License
1.53k stars 711 forks source link

ValueError for to_emails on automated jobs #958

Closed ssaunderss closed 3 years ago

ssaunderss commented 3 years ago

Issue Summary

I've been using sendgrid to send out automated batch emails on a Debian VM. When I run everything manually on the VM, everything works fine, however when I run it from a cron job I'm getting the below value error thrown. I'm using a list of emails as shown in the documentation. I query through my database and create a dictionary that uses a group name as a key and the corresponding value is a list of emails, this is then passed to the Email class's to emails as dict[group]. The query appears to be running fine, I'm a bit stumped about why it can't interpret the list of emails.

Code Snippet

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

class Email:
    def __init__(self, email_list, template_id, from_email, group):
        self.to_emails = email_list
        self.template_id = template_id
        self.from_email = from_email
        self.group = group

    def send_it(self):
        message = Mail(from_email = self.from_email, to_emails = self.to_emails,
            is_multiple=True)

        message.template_id = self.template_id

        try:
            sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
            response = sg.send(message)
            code = response.status_code
            print(f"Response code: {code}, Group: {self.group}")
        except Exception as e:
            print("Error: {0}".format(e))
            print("Can't send email to following group: {}".format(self.group))

Exception/Log

 File ".../main.py", line 28, in <module>
    temp.send_it()
  File ".../send_emails.py", line 15, in send_it
    message = Mail(from_email = self.from_email, to_emails = self.to_emails, is_multiple=True)
  File ".../miniconda3/envs/sendgrid/lib/python3.8/site-packages/sendgrid/helpers/mail/mail.py", line 69, in __init__
    self.add_to(to_emails, global_substitutions, is_multiple)
  File ".../miniconda3/envs/sendgrid/lib/python3.8/site-packages/sendgrid/helpers/mail/mail.py", line 259, in add_to
    self._set_emails(email, global_substitutions, is_multiple, p)
  File ".../miniconda3/envs/sendgrid/lib/python3.8/site-packages/sendgrid/helpers/mail/mail.py", line 153, in _set_emails
    personalization.add_email(emails)
  File ".../miniconda3/envs/sendgrid/lib/python3.8/site-packages/sendgrid/helpers/mail/personalization.py", line 29, in ad$
    raise ValueError('Please use a To, Cc or Bcc object.')
ValueError: Please use a To, Cc or Bcc object.

Technical details:

thinkingserious commented 3 years ago

Hello @ssaunderss,

Please make sure that the emails that you are passing in are of type To, Cc or Bcc. Please see this example. Thanks!

With best regards,

Elmer