Skip to content

Instantly share code, notes, and snippets.

@mrizwan47
Created October 18, 2022 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrizwan47/c9ebbfd68564785ee972dc2a13db5210 to your computer and use it in GitHub Desktop.
Save mrizwan47/c9ebbfd68564785ee972dc2a13db5210 to your computer and use it in GitHub Desktop.
Send Email with Python using Google SMTP
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def notify(receiver_address, subject, mail_content):
sender_address = 'your_email@domain.com'
sender_pass = '16_CHARACTER_PASS_HERE'
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = subject
# The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
# Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender_address, sender_pass)
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
notify('person@example.com', 'Test Email', '''Hello there!
This is a test email.
Thanks!''')

For this, you'll need to sign into your gmail/google workspace account with password. For security reasons, it's prefered to use app password. And if you use 2FA (which you should), you may get "password incorrect" when using your regular password. Follow these steps to create an app password:

  1. Go to your Google Account.
  2. Select Security.
  3. Under "Signing in to Google," select App Passwords.
  4. At the bottom, choose Select app and choose "Mail" and for the Select device option, select "Custom" and enter a descriptive name for the app.
  5. Your password will be shown on screen, it's the 16-character code in the yellow bar.
  6. Copy it and tap Done.

These instructions may change, you can find them (here)[https://support.google.com/mail/answer/185833#app-passwords] as well

Replace the sender_address and sender_pass variables below and use the function where needed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment