網上找到的一般是這樣的:
import smtplib
import email.MIMEMultipart
import email.MIMEText
import email.MIMEBase
import os.path
From = "sender address"
To = "recipients"
file_name = "file name"
server = smtplib.SMTP("smtp server address")
server.login("username","password") #僅smtp伺服器需要驗證時
# 構造MIMEMultipart對象做為根容器
main_msg = email.MIMEMultipart.MIMEMultipart()
# 構造MIMEText對象做為郵件顯示内容并附加到根容器
text_msg = email.MIMEText.MIMEText("this is a test text to text mime")
main_msg.attach(text_msg)
# 構造MIMEBase對象做為檔案附件内容并附加到根容器
contype = 'application/octet-stream'
maintype, subtype = contype.split('/', 1)
## 讀入檔案内容并格式化
data = open(file_name, 'rb')
file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
file_msg.set_payload(data.read( ))
data.close( )
email.Encoders.encode_base64(file_msg)
## 設定附件頭
basename = os.path.basename(file_name)
file_msg.add_header('Content-Disposition',
'attachment', filename = basename)
main_msg.attach(file_msg)
# 設定根容器屬性
main_msg['From'] = From
main_msg['To'] = To
main_msg['Subject'] = "attach test "
main_msg['Date'] = email.Utils.formatdate( )
# 得到格式化後的完整文本
fullText = main_msg.as_string( )
# 用smtp發送郵件
try:
server.sendmail(From, To, fullText)
finally:
server.quit() 要注意的是,如果發送給多人,帶附件的話,收件人位址是一個list,不是string。