Python递归次数统计写法及邮件发送失败后的重新发送
def send(file_list,receivers,subject,acc,times=0):
username = "xxxxxxx"
password = "ppppppp"
sender = username
receivers = receivers
# 如名字所示: Multipart就是多个部分
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ','.join(receivers)
msg['Cc'] = acc
#下面是文字部分,也就是纯文本
context = """
HELLO:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
"""
puretext = MIMEText(context,'html', 'utf-8')
msg.attach(puretext)
# 下面是附件部分 ,这里分为了好几个类型
# 首先是xlsx类型的附件
for i in file_list:
filename = i.strip()
att1 = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename=%s'%filename.split("/")[-1]
msg.attach(att1)
# # jpg类型的附件
# jpgpart = MIMEApplication(open('beauty.jpg', 'rb').read())
# jpgpart.add_header('Content-Disposition', 'attachment', filename='beauty.jpg')
# msg.attach(jpgpart)
# # mp3类型的附件
# mp3part = MIMEApplication(open('kenny.mp3', 'rb').read())
# mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3')
# msg.attach(mp3part)
## 下面开始真正的发送邮件了
print '下面开始真正的发送邮件了'
print('times:',times)
try:
try:
client = smtplib.SMTP_SSL('mail.xxxx.com','465')
client.login(username, password)
client.sendmail(sender, receivers, msg.as_string())
client.quit()
print '带有各种附件的邮件发送成功!'
except Exception as er:
print 'er::',er
print 'Send again::', subject
time.sleep(1)
times += 1
if times<=10:
send(file_list, receivers, subject, acc,times=times)
except smtplib.SMTPRecipientsRefused:
print 'Recipient refused'
except smtplib.SMTPAuthenticationError:
print 'Auth error'
except smtplib.SMTPSenderRefused:
print 'Sender refused'
except smtplib.SMTPException as err:
print 'err:',err