Github에서 찾은 Python 스크립트를 사용하여 첨부 파일이있는 전자 메일을 보내려고합니다. 5 개의 첨부 파일 목록이 있으며 첨부 파일 당 하나의 이메일을 보내려고합니다. 스크립트를 실행하면 첨부 파일이 하나 인 첫 번째 전자 메일과 첨부 파일이 2 개있는 다음 전자 메일을 보냅니다. 다섯 번째 전자 메일에는 목록의 다섯 번째 첨부 파일 대신 다섯 개의 첨부 파일이 모두 있습니다. 첨부 파일 목록을 반복해야하지만 어디에서 그렇게해야하는지 알 수는 없습니다. 어떤 도움이라도 대단히 감사하겠습니다. 스크립트는 다음과 같습니다.첨부 파일 목록에서 Python으로 전자 메일 보내기
attachments = ['file1.zip', 'file2.zip', 'file3.zip', 'file4.zip', 'file5.zip']
host = 'mailer' # specify port, if required, using this notations
fromaddr = '[email protected]' # must be a vaild 'from' address in your GApps account
toaddr = '[email protected]'
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]))
첨부 파일 당 하나의 이메일을 보내고 싶었습니다. 루프 내에서 MSG 코드를 이동하면 필자가 필요로하는 작업을 수행 할 수있었습니다. 고맙습니다 – Christoph