Python Forum

Full Version: How to send email using python?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to send a email using Python. I have an account on Gmail and a proven password (which I will say as ABCD00). When I try to send the email, I get an error:

import smtplib, ssl

sender_email = "my@gmail"
receiver_email = "[email protected]"
message = "Hello, world"

ctx=ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ctx) as server:
   server.login("[email protected]", "ABCD00")
   server.sendmail(sender_email, receiver_email, message)
But I get:
Error:
Traceback (most recent call last): File "./emailer.py", line 15, in <module> server.login("[email protected]", "ABCD00") File "/usr/lib/python3.5/smtplib.py", line 729, in login raise last_exception File "/usr/lib/python3.5/smtplib.py", line 720, in login initial_response_ok=initial_response_ok) File "/usr/lib/python3.5/smtplib.py", line 641, 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 y22sm7196990ejf.108 - gsmtp')
Same thing if I use my as user name. Yet, I can log in with [email protected] and ABCD00 on the browser.
What is the error? How can I send an email with Python?
Thank you
Go into your google account in Safety turn on Access to less secure apps.
Then try again.
Now that I have removed the safeties from Gmail, I can send the email:
import smtplib, ssl

sender_email = "me@gmail"
receiver_email = "[email protected]"
message = "Hello, world"

print("sending email")
ctx=ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ctx) as server:
    server.login("me", password)
    server.sendmail(sender_email, receiver_email, message)
print("sent")
Probably there is a better way, in particular without the use of SSL (but when I tried smtplit.SMTP only, it did not work.

My question now is: how can I add a subject to the email?
Thank you