Skip to content

Instantly share code, notes, and snippets.

@peterjpxie
Created April 5, 2020 07:13
Show Gist options
  • Save peterjpxie/decd14f5926a895f5cb1d842f2350781 to your computer and use it in GitHub Desktop.
Save peterjpxie/decd14f5926a895f5cb1d842f2350781 to your computer and use it in GitHub Desktop.
send_gmail_standard_lib.py
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import smtplib
import os
user = 'your_username@gmail.com'
app_password = 'your_app_password'
host = 'smtp.gmail.com'
port = 465
to = 'your_recipent@gmail.com'
subject = 'test subject'
content_txt = 'mail body content'
attachment = 'test.png'
### Define email ###
message = MIMEMultipart()
# add From
message['From'] = Header(user)
# add To
message['To'] = Header(to)
# add Subject
message['Subject'] = Header(subject)
# add content text
message.attach(MIMEText(content_txt, 'plain', 'utf-8'))
# add attachment
att_name = os.path.basename(attachment)
att1 = MIMEText(open(attachment, 'rb').read(), 'base64', 'utf-8')
att1['Content-Type'] = 'application/octet-stream'
att1['Content-Disposition'] = 'attachment; filename=' + att_name
message.attach(att1)
### Send email ###
server = smtplib.SMTP_SSL(host, port)
server.login(user, app_password)
server.sendmail(user, to, message.as_string())
server.quit()
print('Sent email successfully')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment