使用 Python 脚本发送附件

Send an attachment using Python script

我使用以下 python 脚本通过 gmail 发送附件。但它可用于发送保存在同一文件夹中的附件 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] )

sendMail的第四个参数是一个文件名列表,所以你可以这样做,例如:

sendMail(["name@domain.com"], 
         "Subject", 
         "Dear sir..", 
         ["subdir/file1.zip", "subdirfile.zip"] )

subdir/file1.zip 是相对于您调用脚本的路径。如果您想完全引用其他地方的文件,请使用 /path/to/my/file1.zip,例如/home/user/file1.zip