1

我正在尝试使用我在 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]) )
4

1 回答 1

0

每次循环时,您都向现有消息添加附件,然后发送消息。因此,您将继续积累越来越大的消息并发送每个中间步骤。

不清楚你到底想做什么,但显然不是这个……</p>

如果您想发送一封包含所有五个附件的消息,只需移动发送代码(通过取消缩进将所有内容从循环server = smtplib.SMTP(host)移到循环之外。server.quit()

如果您想发送五封邮件,每封邮件都有一个附件,那么大多数邮件创建代码(从msg = MIMEMultipart()to的所有内容msg.attach(body))通过缩进并将其向下移动几行来进入循环。

如果你想要别的东西,答案几乎肯定会同样微不足道,但是在你解释你想要什么之前,没有人能告诉你怎么做。

于 2013-07-17T00:57:43.500 回答