- Author:杜七
一、需求
日常工作中,需要自動(dòng)執(zhí)行腳本,然后分析數(shù)據(jù),在自動(dòng)發(fā)送到某些人的郵箱中。
Linux下,可以用crontab來(lái)自動(dòng)執(zhí)行shell,或者python腳本。當(dāng)然,Shell也可以自動(dòng)發(fā)送郵件,當(dāng)時(shí)因?yàn)榘踩紤],目前從公司gateway上自動(dòng)發(fā)送郵件需要加密和驗(yàn)證,這就需要特定的配置。
二、Python的自動(dòng)發(fā)送郵件配置
#!/usr/bin/env python
# -*- coding: gbk -*-
from time import strftime,gmtime
import smtplib,mimetypes
from smtplib import SMTP, SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import time
#####################
#要發(fā)給誰(shuí),這里發(fā)給2個(gè)人
date1 = strftime("%Y%m%d",gmtime())
Time=str(time.time())
mailto_list=["xxx@xx.com"]
subject=(date1 + "-" + "SearchDownRight" )
content="測(cè)試郵件"
#####################
mail_host="xxx"
mail_user="xxx@xx.com"
mail_pass="xxx"
mail_port="xxx"
def send_mail(to_list,sub,content):
'''
to_list:發(fā)給誰(shuí)
sub:主題
content:內(nèi)容
send_mail("aaa@xx.com","sub","content")
'''
me=mail_user
print me
# 郵件
msg = MIMEMultipart()
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
# 添加文本內(nèi)容
txt = MIMEText(content)
msg.attach(txt)
# 添加附件
fileName = str("~/data/searchdownright/" + date1 + "TotalshopDownRight.txt")
ctype, encoding = mimetypes.guess_type(fileName)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
att1 = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], _subtype = subtype)
att1.add_header('Content-Disposition', 'attachment', filename = fileName)
msg.attach(att1)
# 服務(wù)器配置
try:
s = smtplib.SMTP_SSL()
s.connect(mail_host)
#設(shè)置服務(wù)器,用戶名、口令以及加密端口
s.login(mail_user,mail_pass)
s.sendmail(me, to_list, msg.as_string())
s.close()
return True
except Exception, e:
print str(e)
return False
#運(yùn)行主程序
if __name__ == '__main__':
if send_mail(mailto_list,subject,content):
print "發(fā)送成功"
else:
print "發(fā)送失敗"
三、執(zhí)行記錄
>>> ================================ RESTART ================================
>>>
xxx@xx.com
發(fā)送成功
當(dāng)然,自己也可以定義郵件內(nèi)容和附件,圖片等等,在MIME做修改就可以了。