Python sendgrid library error when run from command line

Question:

I have a sendgrid account set up and I can use it to send emails through python. When I run it in my spyder IDE it works great, but when run through the windows CMD i get <urlopen error unknown url type: https>.

I tried hard coding the host as sg = SendGridAPIClient(pw,host='https://api.sendgrid.com'). This works in the IDE, but not in CMD, and I get the same error.

I also tried removing the ‘:’ with sg = SendGridAPIClient(pw,host=urllib.parse.quote('https://api.sendgrid.com')). This changesthe error to unknown url type: 'https%3A//api.sendgrid.com/v3/mail/send' This idea was based on the SO post urllib.error.URLError: <urlopen error unknown url type: 'https>.

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import *

api_key='your_api_key'

message = Mail(
from_email='[email protected]',
to_emails='[email protected]',
subject='SUBJECT',
    html_content='some body stuff')

try:
    sg = SendGridAPIClient(api_key)
    response = sg.send(message) #this line throws the error
    print('worked')

except Exception as e:

    print(str(e))

when I run it in the command line I use "python.exe ‘my_scirpt.py’" in the directory of my script.

Asked By: bart cubrich

||

Answers:

I was able to find the answer here: Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

This issue has to do with some DLLs in anaconda. I am not sure what the best fix is for this. I copy pasted the DLLS as shown in one answer here. I am going to copy the text of this answer though, because it is not the top answer on this thread, and this search result does not come up when using sendgrid, so I think my question actually does add to the community. From the other SO post:

"""

I have faced it on 04/2020. These are the options that I tried and the last solution get me through.

Problem:

Requests module works fine when I use in Spyder IDE but when I try to execute the script in windows it fails with SSL error. It works fine for HTTP requests but for HTTPS requests i got SSL error.

I tired with Veify=True, False , also with Certs. Same error.
Removed Certifi – conda remove certifi – Did not work Updated
openssl , certifi – Still same error ( Refer : https://github.com/ContinuumIO/anaconda-issues/issues/494) Added
the path variables – Same error
Created new environment in Anaconda – same error

Solution that fixed it:

Solution from: https://github.com/conda/conda/issues/8273

I have copied the following files from Anaconda3Librarybin to Anaconda3DLL

libcrypto-1_1-x64.* libssl-1_1-x64.*

"""

Answered By: bart cubrich
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.