如何用Python寄信 – Python寄Gmail教學及範例code(SMTP設定)

Tips

在使用通知或是Error通知時會經常使用到Eamil的寄信功能,而在Python之中有library可以使用SMTP client來寄信,這篇文章是要介紹如何用Python寄信。另外,在寄信的時候會使用MIME形式的data這在Python中也有內建的library。

smtplib的使用方式

smtplib的使用方式主要只有在完成MIME data後寄信時才會使用,但是會依據SMTP伺服器的設定可能需要登入等等的處理。

不用登入的場合

(通常不會這樣使用)首先,例如像LAN內部開發用的不需要登入認證的SMTP的伺服器可以用下面的code。這時候就不用自己寫MIME可以直接使用library。

import smtplib
from email.mime.text import MIMEText
 
# 收信寄信人的資料
to_email = "收信人@sample.com"
from_email = "寄件人@sample.com"
 
# MIME text
message = "mail內容"
msg = MIMEText(message, "html")
msg["Subject"] = "mail主旨"
msg["To"] = "收件人mail address"
msg["From"] = "寄件人mail address"
 
# 指定伺服器
server = smtplib.SMTP("SMTP伺服器", port號碼)
# 寄信
server.send_message(msg)
# 關閉伺服器
server.quit()

以上是不需要登入的場合所使用的code。

需要登入的場合

接下來是需要登入的時候所需要做的處理。

login處理

在login的時候可以使用下面的method。

server = smtplib.SMTP("SMTP伺服器", port號碼)
# 認證
server.login(account, password)

debug

為了在沒辦法登入的時候查詢原因,會在下面debug的部分調整成true。

server = smtplib.SMTP("SMTP伺服器", port號碼)
server.set_debuglevel(True)

STARTTLS

如果伺服器可以使用STARTTLS的話可以利用STARTTLS把寄信的過程密碼化。但如果不確定可不可以使用STARTTLS的話可以用下面的code

if server.has_extn('STARTTLS'):
    server.starttls()

SSL

如果是使用SSL通信的話可以參考下面的code。

import ssl
server = smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context())

用Gmail寄信

最後要介紹的是大家最常用的gmail寄信方法。但是要注意的是gmail會查詢你的IP位置,如果沒有辦法查詢到你的domain的話會拒絕連結,因此在使用local的Python時沒有辦法用gmail寄信。所以說要在gmail帳號上設定「允許安全性較低的應用程式」打開。但是這個動作其實在安全上有危險,因此建議可以創立一個練習用的帳號。

首先,我們現來看看使用STARTTLS的範例。

from email.mime.text import MIMEText
import smtplib
 
# SMTP
account = "sample@gmail.com"
password = "password"
 
# 收信寄信人的資料
to_email = "收信人@sample.com"
from_email = "寄件人@gmail.com"
 
# MIME
subject = "test test"
message = "test mail"
msg = MIMEText(message, "html")
msg["Subject"] = subject
msg["To"] = to_email
msg["From"] = from_email
 
# 寄信
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(account, password)
server.send_message(msg)
server.quit()

使用STARTTLS的時候伺服器的port號碼會指定成587。

下面是使用SSL的範例。

import smtplib, ssl
from email.mime.text import MIMEText
 
# SMTP
account = "sample@gmail.com"
password = "password"
 
# 收信寄信人
to_email = "收件人@sample.com"
from_email = "寄件人@gmail.com"
 
# MIME
subject = "test test"
message = "test mail"
msg = MIMEText(message, "html")
msg["Subject"] = subject
msg["To"] = to_email
msg["From"] = from_email
 
server = smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context())
 
server.login(account, password)
server.send_message(msg)
server.quit()

使用SMTP_SSL的時候的port號碼則是要指定465。

追加附件

最後來介紹如何追加附件檔,下面的是在使用gmail的時候想要追加附件檔時的code。

from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
from os.path import basename
 
# SMTP
account = "sample@gmail.com"
password = "password"
 
# 收信寄信人
to_email = "收件人@sample.com"
from_email = "寄件人@gmail.com"
 
# MIME
subject = "test test"
message = "test mail"
msg = MIMEText(message, "html")
msg["Subject"] = subject
msg["To"] = to_email
msg["From"] = from_email
msgattach(MIMEText(message))
 
# 附件
path = "./sample.pdf"
with open(path, "rb") as f:
    part = MIMEApplication(
        f.read(),
        Name=basename(path)
    )
 
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(path)
msg.attach(part)
 
# 寄信
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(account, password)
server.send_message(msg)
server.quit()

留言