2
我使用以下python腳本通過gmail發送附件。但它可以用於發送保存在同一個文件夾中的附件,python腳本被保存。我想發送保存在不同文件夾中的附件。我怎樣才能通過修改這個腳本來做到這一點?謝謝。使用Python腳本發送附件
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import datetime
smtpUser = ' '
smtpPass = ' '
toAdd = ' '
fromAdd = smtpUser
today = datetime.date.today()
subject = 'Data File 01 %s' % today.strftime('%Y %b %d')
header = 'To :' + toAdd + '\n' + 'From : ' + fromAdd + '\n' + 'Subject : ' + subject + '\n'
body = 'This is a data file on %s' % today.strftime('%Y %b %d')
attach = 'Data on %s.csv' % today.strftime('%Y-%m-%d')
print header
def sendMail(to, subject, text, files=[]):
assert type(to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = smtpUser
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for file in files:
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)
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo_or_helo_if_needed()
server.starttls()
server.ehlo_or_helo_if_needed()
server.login(smtpUser,smtpPass)
server.sendmail(smtpUser, to, msg.as_string())
print 'Done'
server.quit()
sendMail([toAdd], subject, body, [attach])
該問題詢問有關在腳本工作目錄之外發送文件的問題。考慮在你的答案中包括絕對路徑。 –
我把「不同的文件夾」作爲一個子目錄,但它當然也可能在其他地方完成,謝謝你的提示 – hansaplast