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()