我正在尝试使用我在 Github 上找到的 Python 脚本来发送带有附件的电子邮件。我有一个包含 5 个附件的列表,并希望每个附件发送一封电子邮件。当我运行脚本时,它会发送第一封带有一个附件的电子邮件,下一封带有 2 个附件的电子邮件,依此类推。第 5 封电子邮件包含所有 5 个附件,而不是列表中的第 5 个附件。我相信我需要遍历附件列表,但不知道在哪里这样做。任何帮助将不胜感激。脚本如下。
attachments = ['file1.zip', 'file2.zip', 'file3.zip', 'file4.zip', 'file5.zip']
host = 'mailer' # specify port, if required, using this notations
fromaddr = 'test@localhost' # must be a vaild 'from' address in your GApps account
toaddr = 'target@remotehost'
replyto = fromaddr # unless you want a different reply-to
msgsubject = 'Test ZIP'
htmlmsgtext = """<h2>TEST</h2>"""
######### In normal use nothing changes below this line ###############
import smtplib, os, sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
from HTMLParser import HTMLParser
# A snippet - class to strip HTML tags for the text version of the email
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
########################################################################
try:
# Make text version from HTML - First convert tags that produce a line break to carriage returns
msgtext = htmlmsgtext.replace('</br>',"\r").replace('<br />',"\r").replace('</p>',"\r")
# Then strip all the other tags out
msgtext = strip_tags(msgtext)
# necessary mimey stuff
msg = MIMEMultipart()
msg.preamble = 'This is a multi-part message in MIME format.\n'
msg.epilogue = ''
body = MIMEMultipart('alternative')
body.attach(MIMEText(msgtext))
body.attach(MIMEText(htmlmsgtext, 'html'))
msg.attach(body)
if 'attachments' in globals() and len('attachments') > 0:
for filename in attachments:
f=filename
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % f)
msg.attach(part)
msg.add_header('From', fromaddr)
msg.add_header('To', toaddr)
msg.add_header('Subject', msgsubject)
msg.add_header('Reply-To', replyto)
server = smtplib.SMTP(host)
server.set_debuglevel(False) # set to True for verbose output
server.sendmail(msg['From'], [msg['To']], msg.as_string())
print 'Email sent with filename: "%s"' % f
server.quit()
except:
print ('Email NOT sent to %s successfully. %s ERR: %s %s %s ', str(toaddr), str(sys.exc_info()[0]), str(sys.exc_info()[1]), str (sys.exc_info()[2]) )