Photo by Anete Lūsiņa / Unsplash

Background

剛好最近工作要用到, 網路上有很多教學. 但還是記錄一下.

Start

Allow "less secure apps" on your account

想利用gmail來寄信. 首先把account的less secure apps開關打開. 這樣才會通過google的 SMTP Authentication.

https://myaccount.google.com/lesssecureapps

basic

基本的send email code. 把下面大寫的部分換成你自己想要填入的東西.

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

msg = MIMEMultipart()
msg['From'] = "FROM_EMAIL"
msg['To'] = "TO_EMAIL"
msg['Subject'] = "SUBJECT"

body = "YOUR MESSAGE HERE"
msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("YOUR_EMAIL", "EMAIL_PASSWORD")
text = msg.as_string()
server.sendmail(msg['From'], msg['To'], text)
server.quit()

attach file

如果你有附加檔案的需求. 那就用下面的code即可. 把_file換成你想夾帶的檔案.

import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

msg = MIMEMultipart()
msg['From'] = "FROM_EMAIL"
msg['To'] = "TO_EMAIL"
msg['Subject'] = "SUBJECT"

body = "YOUR MESSAGE HERE"
msg.attach(MIMEText(body, 'plain'))

_file = 'tmp.csv'
with open(_file, 'rb') as fp:
    att_file = MIMEBase('application', "octet-stream")
    att_file.set_payload(fp.read())
    encoders.encode_base64(att_file)
    att_file.add_header('Content-Disposition', "attachment; filename= %s" % _file)

msg.attach(att_file)

text = msg.as_string()
server.sendmail(msg['From'], msg['To'], text)
server.quit()

Reference