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=["xxx@xx.com"]
subject=(date1 + "-" + "SearchDownRight" )
content="测试邮件"


#####################
mail_host="xxx"
mail_user="xxx@xx.com"
mail_pass="xxx"
mail_port="xxx"

def send_mail(to_list,sub,content):
    '''
    to_list:发给谁
    sub:主题
    content:内容
    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)
    
    # 添加文本内容
    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 ================================
>>> 
xxx@xx.com
发送成功

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,781评论 6 427
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,282评论 19 139
  • GitHub 上有一个 Awesome - XXX 系列的资源整理,资源非常丰富,涉及面非常广。awesome-p...
    若与阅读 19,173评论 4 417
  • 环境管理管理Python版本和环境的工具。p–非常简单的交互式python版本管理工具。pyenv–简单的Pyth...
    MrHamster阅读 9,289评论 1 61
  • 写在前面 Backbone的加载 正文 Backbone.View的基本用法 Backbone.View方法用于定...
    Locdee_落地阅读 4,649评论 0 0

友情链接更多精彩内容