加上 smtplib.SMTP_SSL(mail_host, 465) #阿里云把25端口封掉了
附完整代码
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time
def get_current_time():
return str(time.strftime('%Y-%m-%d %H'))
current_time = get_current_time()
filename='/opt/user/liustockEarlyWarning/data/stockEarlyWarning-20180525.xlsx' #附件地址
areceiver = '***@centchain.com'
acc = ''
def send_mail(to_list,sub,context,filename): #to_list:收件人;sub:主题;content:邮件内容
mail_host="smtp.***.com" #设置服务器
mail_user="****.com" #用户名
mail_pass="*****" #口令
mail_postfix="****.com" #发件箱的后缀
me="大数据"+"<"+mail_user+"@"+mail_postfix+">" #这里的“服务器”可以任意设置,收到信后,将按照设置显示
msg = MIMEMultipart() #给定msg类型
msg['Subject'] = sub #邮件主题
msg['From'] = me
msg['To'] = areceiver
msg['Cc'] = acc
msg.attach(context)
#构造附件1
att1 = MIMEText(open(filename, 'rb').read(), 'xls', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment;filename='+filename[-13:-1]#这里的filename可以任意写,写什么名字,邮件中显示什么名字,filename[-6:]指的是之前附件地址的后6位
msg.attach(att1)
try:
# s = smtplib.SMTP()
s = smtplib.SMTP_SSL(mail_host, 465) #阿里云把25端口封掉了
s.connect(mail_host) #连接smtp服务器
s.login(mail_user,mail_pass) #登陆服务器
s.sendmail(me, areceiver.split(',')+ acc.split(','), msg.as_string()) #发送邮件
s.close()
return True
except Exception:
return False
if __name__ == '__main__':
# mailto_list=['***@centchain.com','***@centchain.com']
data=pd.read_excel(filename, sheet_name=0)
a=pd.DataFrame(data)
b=a.iloc[:,0].size
sub="万达影票库存"
d='' #表格内容
for i in range(b):
d=d+"""
<tr>
<td>""" + str(a.index[i]) + """</td>
<td>""" + str(a.iloc[i][0]) + """</td>
<td width="60" align="center">""" + str(a.iloc[i][1]) + """</td>
</tr>"""
html = """\
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<div id="container">
<p><strong>这是万达影票"""+current_time+"""时的库存:</strong></p>
<div id="content">
<table width="30%" border="2" bordercolor="black" cellspacing="0" cellpadding="0">
<tr>
<td width="40"><strong></strong></td>
<td width="50"><strong>商品名</strong></td>
<td width="60" align="center"><strong>库存</strong></td>
</tr>"""+d+"""
</table>
</div>
</div>
</div>
</body>
</html>
"""
context = MIMEText(html,_subtype='html',_charset='utf-8') #解决乱码
if send_mail(areceiver.split(',')+ acc.split(','),sub,context,filename):
print ("发送成功")
else:
print( "发送失败")

1272





