0

I am trying to send email using python. I tried many solution on Stackoverflow but none worked.

my code is -

import smtplib
fromaddr = 'user_me@gmail.com'
toaddrs  = 'user_you@gmail.com'
msg = 'msg text here'
username = 'user_me@gmail.com'
password = 'pwd'
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

Code remain stuck at line server = smtplib.SMTP('smtp.gmail.com',587)

Tried port 465 and get this error -

Traceback (most recent call last):
  File "gmail-python.py", line 130, in <module>
    mainFunction()
  File "gmail-python.py", line 101, in mainFunction
    mail = smtplib.SMTP('smtp.gmail.com', 465)
  File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python2.7/smtplib.py", line 317, in connect
    (code, msg) = self.getreply()
  File "/usr/lib/python2.7/smtplib.py", line 368, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

tried this - smtplib.SMTP_SSL('smtp.gmail.com',465) and got this error

 raise SMTPException("STARTTLS extension not supported by server.")
smtplib.SMTPException: STARTTLS extension not supported by server.

removing server.ehlo() had no effect. removing server.starttls() caused below error -

raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbsV\n5.7.14 3GHIcJvaksu56NrYm76aC0MqGI_sFI2cNaKSoFX6CV7TlyW593zn4dnJN7mG4TGI7edfcj\n5.7.14 l-MOV1Sb0Joyewnax8dxiL5BQ28Gg3UsWDfibI5TZ-tEaqqpL4WEzX5hsqYg6ZIQlczjyq\n5.7.14 UbElUx1C2E0QBt-X3uCuueb06uPBqehnwNV-hOlYFCgZpxRR9fdi-rO65oD5c1asYyGaTh\n5.7.14 1VRKgMYJp-o_uMhMjGEyJWKLLYX3A> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14  Learn more at\n5.7.14  https://support.google.com/mail/answer/78754 r85sm13251579pfr.48 - gsmtp')

I have enabled less secure app access in my account. Python version 2.7.6 on ubuntu.

Anurag Rana
  • 1,429
  • 2
  • 24
  • 48
  • Hm. I just tried your exact code and it works fine on Python 3.4.3/Win32. I tried almost identical on other platforms, too. Your error happens before any mention of your account, so it has nothing to do with specific Gmail account. Have you tried http://stackoverflow.com/questions/11545166/sending-email-in-python-did-google-change-something-regarding-gmail#comment15266517_11545166 to confirm connectivity is there? (telnet smtp.gmail.com 587) What python version do you use? – Jakub P. May 27 '16 at 12:46
  • python version 2.7.6 on ubuntu – Anurag Rana May 27 '16 at 13:07

1 Answers1

0

Try after turning of Gmail's Security Feature Here. This may be preventing 3rd party application from accessing Gmail for security purpose

https://www.google.com/settings/security/lesssecureapps

amitnair92
  • 487
  • 7
  • 20