0

I am using this following code however I keep getting an error.. what am I doing wrong.,

import os
import smtplib

sender_email = "myemail@gmail.com"
rec_email = "myemail@gmail.com"
username = "myemail@gmail.com"
password = input(str("EnterPassword"))
message = "Hey, this was sent using python"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
print("connected")
server.login(username,password)
print("Login success")
server.sendmail(sender_email,rec_email,message)
print("Email has been sent")

Error:

connected
Traceback (most recent call last):
  File "C:/Users/<user>/PycharmProjects/Report/main.py", line 12, in <module>
    server.login(username,password)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\smtplib.py", line 730, in login
    raise last_exception
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\smtplib.py", line 721, in login
    initial_response_ok=initial_response_ok)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\smtplib.py", line 642, in auth
    raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials q15sm575467pje.29 - gsmtp')

Process finished with exit code 1
Grismar
  • 27,561
  • 4
  • 31
  • 54
  • 3
    Have you looked at the website suggested in the error message? Clearly, your username and password are not accepted - you're likely to find reasons why that can happen (other than typos) at that URL. – Grismar Sep 16 '20 at 00:49
  • Note that the SMTP server at that address requires SSL, so you likely need to start TLS. Similar question here: https://stackoverflow.com/questions/37181291/smtp-sending-e-mail-issue-with-gmail – Grismar Sep 16 '20 at 00:50

1 Answers1

1

First of all, make sure your gmail email and password is correct. Verify by login through a browser.

Then try adding an Extended HELO (ehlo) message after you set up your server.

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()

Besides, gmail requires you to:

Only after these steps, gmail allows third party libraries to allow SMTP login.

PaxPrz
  • 1,778
  • 1
  • 13
  • 29