Home > Enterprise >  Python Sending email using SMTP - target machine actively refused connection
Python Sending email using SMTP - target machine actively refused connection

Time:11-22

I am trying to send email internally within work using the smtplib package in Python. I am running this script behind a VPN using the same proxy settings for R and Spyder. I use the following code which was adapted from mkyoung.com

import smtplib

to = '[email protected]'
corp_user = '[email protected]'
corp_pwd = 'password'
smtpserver = smtplib.SMTP_SSL(local_hostname="smtp://foo-corporate.com", port = 25)
smtpserver.connect()

Once i try the last line smtpserver.connect(), I get the error message:

[WinError 10061] No connection could be made because the target machine actively refused it

This would suggest that the server is not accepting SMTP requests. However if i execute the same script in R using the Blastula package It works fine. Can anyone suggest how I can trouble shoot this?

library(blastula)

create_smtp_creds_key(
  id = "email_creds",
  user = "[email protected]",
  host = "smtp://foo-corporate.com",
  port = 25,
  use_ssl = TRUE
)

email <-
  compose_email(
    body = md(" Hello, 
        This is a test email
        "))
  
# Sending email by SMTP using a credentials file
email %>%
  smtp_send(
    to = "[email protected]",
    from = "[email protected]",
    subject = "Testing the `smtp_send()` function",
    credentials = creds_key("email_creds")
  )




CodePudding user response:

Seems like the context is not needed at all.

This is an example using TLS. Give it a try, at least in my environment, this worked.

import smtplib

smtp_server = 'mail.example.com'
port = 587  # For starttls
sender_email = "[email protected]"
receiver_email = '[email protected]'
password = r'password'
message = f'''\
From: from-name <[email protected]>
To: to-name <[email protected]>
Subject: testmail

testmail

'''
try:
    server = smtplib.SMTP(smtp_server, port)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)    
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit()

CodePudding user response:

Hi @user99999 and @Ovski

Thank you for investigating this for me. I managed to finally get it working with the below code


import smtplib
import ssl

to = '[email protected]'
corp_user = '[email protected]'
corp_pwd = 'password'
smtpserver = smtplib.SMTP_SSL("smtp://foo-corporate.com")
smtp_server.ehlo()
smtp_server.login(corp_user, corp_pwd)
msg_to_send = '''
hello world!
'''

smtp_server.sendmail(user,to,msg_to_send)
smtp_server.quit()


  • Related