Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send email with Gmail Python

I am attempting to send an email, but I run into this error: smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor d2sm13023190qkl.98 - gsmtp')

In the web URL i dont see anything super useful, would anyone have any tips? For SO purposes I left the email account passwords as test versus sharing my person info..

import smtplib
import ssl


# User configuration
sender_email = '[email protected]'
receiver_email = '[email protected]'
password = 'test'



# Email text
email_body = '''
    This is a test email sent by Python. Isn't that cool?
'''

# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, email_body)
print('Email sent!')

print('Closing the server...')
server.quit()
like image 516
bbartling Avatar asked Aug 04 '26 05:08

bbartling


1 Answers

I tried my best... I think this should work!

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

email = "[email protected]" # the email where you sent the email
password = "yourPassword"
send_to_email = "[email protected]" # for whom
subject = "Gmail"
message = "This is a test email sent by Python. Isn't that cool?!"

msg = MIMEMultipart()
msg["From"] = email
msg["To"] = send_to_email
msg["Subject"] = subject

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

server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()
like image 179
ŁeZard Avatar answered Aug 05 '26 18:08

ŁeZard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!