kuldeep sharma
kuldeep sharma

Reputation: 41

not able to send mail using python

I'm using the following method to send mail from Python using SMTP. I have tried many times to run this code which is right but it always shows me the same error is there anyone who can help me in this.

import smtplib

TO = '[email protected]'

SUBJECT = 'TEST MAIL'
TEXT = 'Here is a message from python.'

gms = '[email protected]'
gm = 'www'

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()`enter code here`
server.starttls()
server.login(gms, gm)

BODY = '\r\n'.join(['To: %s' % TO,
                    'From: %s' % gms,
                    'Subject: %s' % SUBJECT,
                    '', TEXT])

try:
    server.sendmail(gms, [TO], BODY)
    print('email sent')
finally:
    print('Error sending mail')
server.quit()

And the errors are:-

 Traceback (most recent call last):
      File "E:/projects/Intern/Mail/Maill.py", line 10, in <module>
        server = smtplib.SMTP('smtp.gmail.com', 587)
      File "C:\Users\KD\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 251, in __init__
        (code, msg) = self.connect(host, port)
      File "C:\Users\KD\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 336, in connect
        self.sock = self._get_socket(host, port, self.timeout)
      File "C:\Users\KD\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 307, in _get_socket
        self.source_address)
      File "C:\Users\KD\AppData\Local\Programs\Python\Python36\lib\socket.py", line 724, in create_connection
        raise err
      File "C:\Users\KD\AppData\Local\Programs\Python\Python36\lib\socket.py", line 713, in create_connection
        sock.connect(sa)
    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

Upvotes: 2

Views: 2808

Answers (2)

dsaves
dsaves

Reputation: 301

Check your firewall and network settings and make sure that you have port 587 open! The error states that you can't even open a connection w/ smtp.gmail.com.

Upvotes: 0

Isa Hassen
Isa Hassen

Reputation: 300

This is most likely a local issue with your firewall or ISP, which is probably blocking outgoing SMTP connections. There is no other reason why smtp.gmail.com should timeout - it should always be online. Even if the credentials were invalid, you usually get a smart error code from the gmail server.

Check your antivirus software or firewall. Or try using a Web/HTTP API for sending email, instead of SMTP.

Upvotes: 3

Related Questions