Sendgrid module

I’m trying to import the sendgrid module, but I’m getting this error:

ImportError: No module named sendgrid

I checked the documentation and sendgrid is listed (https://anvil.works/doc/#-div-id-python_packages-python-packages-div- )

Any idas on how I can get this going?

Make sure you’re using this server side and not client side.

Also, which version of python are you using? I think you can only import libraries using the full versions (ie with a paid account).

Thanks for the reply David.

And yes, it was server side.

I switched to using the requets module and this gave a much more helpful error message, saying I needed to switch to a different python runtime.

SO I’ve changed from Python (Restricted) to Python 2.6 , but it is now saying I have to wait up to 24 hours for it to be enabled

image

Ah yes - they do that manually at Anvil central.

Anvil Central, thats got a nice sound to it.

Or maybe the Anvil Forge… :slight_smile:

1 Like

Forge?! I’ll have you know our anvils are 100% authentic! :wink:

2 Likes

Hey phil! I am just getting started w/ sendgrid and I have run into a few issues, maybe you could point me in the right direction.

I tried sending email by replicating the given curl example using requests like this:

@anvil.server.http_endpoint('/send')
def send():
  a = requests.post(
    'https://api.sendgrid.com/v3/mail/send',
    data= {"personalizations":[{"to":[{"email":"brian@myradvocate.com","name":"Docs Team"}],
          "subject":"Ahoy, World!"}],
          "content": [{"type": "text/plain", "value": "Ahoy from Twilio and SendGrid!"}],
          "from":{"email":"ahoy@example.com","name":"Hoot the Owl"},
          "reply_to":{"email":"ahoy@example.com","name":"Hoot the Owl"}},
    headers={"authorization":str("Bearer "+anvil.secrets.get_secret('sendgrid_api_key')), "content-type":"application/json"}
  ).json()
  return a

which returns this error:

{“errors”:[{“field”:null,“message”:“Bad Request”,“help”:null}]}

I saw that sendgrid was available in anvil, so I ran the given python example as so:

@anvil.server.http_endpoint('/sendit')
def sendit():
  message = Mail(
    from_email='from_email@example.com',
    to_emails='brian@myradvocate.com',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
  try:
      sg = SendGridAPIClient(anvil.secrets.get_secret('sendgrid_api_key'))
      response = sg.send(message)
      print(response.status_code)
      print(response.body)
      print(response.headers)
  except Exception as e:
      print(e.message)
  return message 

sadly this was unsuccesful and, in the app logs I found this message:

TypeError: init() got an unexpected keyword argument ‘html_content’

have you or anyone else here successfully sent sendgrid emails via anvil?

*** UPDATE ***

I saw here that the version of sendgrid available in anvil is an older version (5.3.0). makes sense now.