Search code examples
pythonpython-3.xsmtpsmtplib

I got TimeoutError when sending mails with SMTP using Python 3


I'm using Python3.7 and I got the following error when I run my code:

TimeoutError: [WinError 10060] 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

here's my code:

import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

server = smtplib.SMTP('smtp.gmail.com', 25)
server.connect("smtp.gmail.com",465)

server.ehlo()

with open('password.txt', 'r') as f:
   password = f.read()

server.login('mymail@gmail.com', password)

msg = MIMEMultipart()
msg['From'] = 'mymail@gmail.com'
msg['To'] = 'mymail2@yahoo.com'
msg['Subject'] = 'Mail testing with Python'

with open('message.txt', 'r') as f:
    message = f.read()

msg.attach(MIMEText(message, 'plain'))

text = msg.as_string()
server.sendmail('mymail@gmail.com', 'mymail2@yahoo.com', text)

what seems to be the problem? is there any mistake in my code or is it just my network connection?


Solution

  • First of all, for gmail to work properly with python script, you need to configure gmail to allow low security apps. I assume you have already done that part, otherwise you can check on gmail help.

    Gmail help on turn on less secure app

    This is the script that should send your email:

    import smtplib
    
    from email.mime.text import MIMEText
    
    from email.mime.multipart import MIMEMultipart
    
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    
    server.ehlo()
    
    server.login('mymail@gmail.com', "your password")
    
    
    msg = MIMEMultipart('alternative',)
    msg['From'] = 'mymail@gmail.com'
    msg['To'] = 'mymail2@yahoo.com'
    msg['Subject'] = 'Mail testing with Python'
    
    with open('message.txt', 'r') as f:
        message = f.read()
    
    msg.attach(MIMEText(message, 'plain'))
    
    text = msg.as_string().encode('utf8')
    
    server.sendmail('mymail@gmail.com', 'mymail2@yahoo.com', text)