Search code examples
python-3.xbatch-filescheduled-taskssmtplib

Why do I get a "No SSL included in this python" when I run script using smtplib from a batch file but not when I run it manually?


I am able to send emails fine from a script using smtplib, but when I try to run it from a batch file or from task scheduler everything works except the email doesn't send at the end. I get a "No SSL" error.

I'm running this from a conda environment, but I've double checked that I calling python from within that environment and not base.

python version 3.7.3.

I call this function from another script and pass the email subject and message to the function.

def send_log_email(subject, message):
     smtp_server = 'smtp.office365.com'
     smpt_port = 25
     sender = '[emailed address]'
     pw = '[password]'

     msg = MIMEMultipart()
     msg['From'] = sender
     msg['To'] = sender
     msg['Subject'] = subject
     msg.attach(MIMEText(message))

     conn = SMTP(smtp_server,smtp_port)
     conn.set_debuglevel(1)
     conn.starttls()
     conn.login(sender, pw)
     conn.sendmail(sender, sender, msg.as_string())

Here's the error I get when I run it from a batch file.

send: 'ehlo []\r\n'
reply: b'250-Outlook Hello [IP]\r\n'
reply: b'250-SIZE 157286400\r\n'
reply: b'250-PIPELINING\r\n'
reply: b'250-DSN\r\n'
reply: b'250-ENHANCEDSTATUSCODES\r\n'
reply: b'250-STARTTLS\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-BINARYMIME\r\n'
reply: b'250-CHUNKING\r\n'
reply: b'250 SMTPUTF8\r\n'
reply: retcode (250); Msg: b'outlook' Hello [IP]\nSIZE 157286400\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\nSTARTTLS\n8BITMIME\nBINARYMIME\nCHUNKING\nSMTPUTF8'
send: 'STARTTLS\r\n'
reply: b'220 2.0.0 SMTP server ready\r\n'
reply: retcode (220); Msg: b'2.0.0 SMTP server ready'
Traceback (most recent call last):
  File "path\my_script.py", line 136, in <module>
    send_log_email(result, message)
  File "path\my_email_script.py", line 31, in send_log_email
    conn.starttls()
  File "python_path\custom_environment\lib\smtplib.py", line 756, in starttls
    raise RuntimeError("No SSL support included in this Python")
RuntimeError: No SSL support included in this Python

Solution

  • Contrary to most of what I found online, I needed to activate the environment in the batch file to get the script to run properly from task scheduler.

    call C:\ProgramData\Anaconda3\Scripts\activate.bat
    "C:\my_env_path\python.exe" "C:\my_script_path\my_script.py" 
    call C:\ProgramData\Anaconda3\Scripts\deactivate.bat
    

    Not sure if I actually need to deactivate the environment or not, but there it is.