从附件列表中使用Python发送电子邮件

时间:2013-07-17 00:47:04

标签: python email

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

1 个答案:

答案 0 :(得分:0)

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

目前尚不清楚你真正想做什么,但显然不是这个......

如果您要发送一封包含所有五个附件的邮件,只需移动发送代码(从server = smtplib.SMTP(host)server.quit()的所有内容,只需将其隐藏起来即可。

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

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