[英]Sending emails with Python from a list of attachments
我正在嘗試使用在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]) )
每次循環時,您都將附件添加到現有郵件中,然后發送該郵件。 因此,您將不斷積累越來越多的消息並發送每個中間步驟。
目前尚不清楚您實際上想做什么,但顯然不是這樣…
如果要發送一封包含所有五個附件的郵件,只需將發送代碼(所有內容從server = smtplib.SMTP(host)
移到循環外,通過不縮進將其移動到server.quit()
server = smtplib.SMTP(host)
即可。
如果要發送五封郵件,每封郵件都帶有一個附件,則可以通過縮進並將其向下移動幾行來將大多數郵件創建代碼(從msg = MIMEMultipart()
到msg.attach(body)
)發送到循環中。
如果您還想要其他東西,答案幾乎肯定是微不足道的,但是在您解釋您想要的東西之前,沒有人會告訴您如何做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.