1

Python sending a reply to an existing email in a gmail account fails with this error:

A connection attempt failed because the connected party did not     
properly respond after a period of time, or established connection
failed because connected host has failed to respond

I have an email in my gmail account sent by an automation entity. With my python code, I receive its UID and try to reply to that, but it fails.

I read several stackoverflow posts on gmail reply and even read the https://www.rfc-editor.org/rfc/rfc2822#appendix-A.2 and Gmail Send Email As Reply

# An automation entity (abc@myNet.email.com) sends an email to my gmail Account xyz@gmail.com 
    
    from: abc@myNet.email.com  
    to: xyz@gmail.com        
    date: Jan 3, 2019, 7:19 AM 
    subject: abc Email Automation (Id=100) 
    security:  No encryption Learn more 

#Using IMAP4 I retrieve the UID of the last email with a given subject ("abc Email Automation"), 
    say --> 904

 # In python gmail reply 
    message = "I received your email"
    to_email = "abc@myNet.email.com "
    servername = 'smtp.gmail.com'
    username = "xyz@gmail.com"
    password = "blahblah"   # This is password to xyz@gmail.com

    msg = MIMEMultipart()
    msg['From'] = "xyz@gmail.com"
    msg['To'] = "abc@myNet.email.com"
    msg['Subject'] = "Re: abc Email Automation (Id=100)"
    msg['In-Reply-To'] = 904
    msg.attach(MIMEText(message))
    server = smtplib.SMTP(servername)
    try:
        server.set_debuglevel(True)
        server.ehlo()
        if server.has_extn('STARTTLS'):
            server.starttls()
            server.ehlo()  # re-identify ourselves over TLS connection

        server.login(username, password)
        server.sendmail(username, [to_email], msg.as_string())
    finally:
        print ("Can not send reply email")
        server.quit()
Community
  • 1
  • 1
Ghost
  • 549
  • 8
  • 29

1 Answers1

2

I would bet you have the port wrong. https://support.google.com/a/answer/176600?hl=en gives you the port to use - you're using TLS atop SMTP, not SSL I think ( I know, it's confusing :P) so you should be setting port 587.

server = smtplib.SMTP(servername, 587)
erik258
  • 14,701
  • 2
  • 25
  • 31
  • Thanks I tried: try: server = smtplib.SMTP(servername, 587) server.set_debuglevel(True) server.ehlo() if server.has_extn('STARTTLS'): server.starttls() server.ehlo() # re-identify ourselves over TLS connection server.login(username, password) server.sendmail(username, [to_email], msg.as_string()) still getting the same error – Ghost Jan 03 '19 at 16:48
  • 1
    Thanks Dan.. I managed to get it working, you were right. This is what I did gmail = smtplib.SMTP('smtp.gmail.com', 587) gmail.ehlo() gmail.starttls() gmail.login("xyz@gmail.com", "blahblah") – Ghost Jan 03 '19 at 17:19