简体   繁体   English

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

[英]Sending emails with Python from a list of attachments

I am trying to use a Python script I found on Github to send email with attachments. 我正在尝试使用在Github上找到的Python脚本发送带有附件的电子邮件。 I have a list of 5 attachments and want to send one email per attachment. 我有5个附件的列表,希望每个附件发送一封电子邮件。 When I run the script it sends the first email with one attachment and the next email with 2 attachments and so on. 当我运行脚本时,它将发送带有一个附件的第一封电子邮件,以及带有2个附件的下一封电子邮件,依此类推。 The 5th email has all 5 attachments instead of the 5th attachment in the list. 第5封电子邮件具有所有5个附件,而不是列表中的第5个附件。 I believe that I need to iterate through the list of attachments but cannot figure out where to do so. 我认为我需要遍历附件列表,但无法弄清楚在哪里进行。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Script is below. 脚本如下。

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]) )

Each time through the loop, you add an attachment to the existing message, then send the message. 每次循环时,您都将附件添加到现有邮件中,然后发送该邮件。 So, you're going to keep accumulating a bigger and bigger message and sending each intermediate step. 因此,您将不断积累越来越多的消息并发送每个中间步骤。

It's not clear what you actually want to do, but obviously not this… 目前尚不清楚您实际上想做什么,但显然不是这样…

If you want to send one message with all five attachments, just move the sending code (everything from server = smtplib.SMTP(host) to server.quit() outside the loop by unindenting it. 如果要发送一封包含所有五个附件的邮件,只需将发送代码(所有内容从server = smtplib.SMTP(host)移到循环外,通过不缩进将其移动到server.quit() server = smtplib.SMTP(host)即可。

If you want to send five messages, each with one attachment, most the message-creating code (everything from msg = MIMEMultipart() to msg.attach(body) ) into the loop by indenting it and moving it down a couple lines. 如果要发送五封邮件,每封邮件都带有一个附件,则可以通过缩进并将其向下移动几行来将大多数邮件创建代码(从msg = MIMEMultipart()msg.attach(body) )发送到循环中。

If you want something else, the answer will almost surely be similarly trivial, but nobody can tell you how to do it until you explain what it is you want. 如果您还想要其他东西,答案几乎肯定是微不足道的,但是在您解释您想要的东西之前,没有人会告诉您如何做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM