Python与自动发送邮件

  • Author:杜七

一、需求

日常工作中,需要自动执行脚本,然后分析数据,在自动发送到某些人的邮箱中。
Linux下,可以用crontab来自动执行shell,或者python脚本。当然,Shell也可以自动发送邮件,当时因为安全考虑,目前从公司gateway上自动发送邮件需要加密和验证,这就需要特定的配置。

二、Python的自动发送邮件配置

#!/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

#####################
#要发给谁,这里发给2个人
date1 = strftime("%Y%m%d",gmtime())
Time=str(time.time())
mailto_list=["[email protected]"]
subject=(date1 + "-" + "SearchDownRight" )
content="测试邮件"


#####################
mail_host="xxx"
mail_user="[email protected]"
mail_pass="xxx"
mail_port="xxx"

def send_mail(to_list,sub,content):
    '''
    to_list:发给谁
    sub:主题
    content:内容
    send_mail("[email protected]","sub","content")
    '''
    me=mail_user
    print me

    # 邮件
    msg = MIMEMultipart()
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
    
    # 添加文本内容
    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)  

    # 服务器配置
    try:
        s = smtplib.SMTP_SSL()
        s.connect(mail_host)
    
    #设置服务器,用户名、口令以及加密端口
        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
        
#运行主程序
if __name__ == '__main__':
    
    if send_mail(mailto_list,subject,content):
        print "发送成功"
    else:
        print "发送失败"

三、执行记录

>>> ================================ RESTART ================================
>>> 
[email protected]
发送成功

当然,自己也可以定义邮件内容和附件,图片等等,在MIME做修改就可以了。

你可能感兴趣的:(Python与自动发送邮件)