我正在嘗試創建一個腳本,它將使用Gmail郵件發送多個附件。下面的代碼發送電子郵件,但不附件。預期用途是cron幾個db查詢並通過電子郵件發送結果。總會有2個文件,每天的文件名稱會有所不同,因爲報告的date
位於文件名中。否則,我會剛剛使用:Gmail Python多個附件
part.add_header('Content-Disposition',
'attachment; filename="absolute Path for the file/s"')
任何幫助非常感謝。
import os
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders
#Set up crap for the attachments
files = "/tmp/test/dbfiles"
filenames = [os.path.join(files, f) for f in os.listdir(files)]
#print filenames
#Set up users for email
gmail_user = "[email protected]"
gmail_pwd = "somepasswd"
recipients = ['recipient1','recipient2']
#Create Module
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject
msg.attach(MIMEText(text))
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
#get all the attachments
for file in filenames:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(file, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
#send it
mail(recipients,
"Todays report",
"Test email",
filenames)