前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python编写的Linux邮件发送工具

Python编写的Linux邮件发送工具

作者头像
py3study
发布2020-01-17 11:47:48
7050
发布2020-01-17 11:47:48
举报
文章被收录于专栏:python3python3

之前有用过Linux自带的mail工具来定时发送邮件,但是要装mailx还有配mail.rc,这还比较正常,关键是到了ubantu下这工具用起来真是操蛋,如果哪天其他的unix like操作系统也有需求,那就太麻烦了,所以我用自带的python2.6.6和自带的邮件相关的库写了个小工具,使用步骤如下:

一、申请一个163邮箱,作为发件箱。

不用qq邮箱是因为,qq邮箱的SMTP服务器需要独立的密码,比较麻烦一点。

二、创建如下脚本,改名为SendMail.py:

注意将以下脚本中的from_addr和password改为你自己的163邮箱和密码即可。

代码语言:javascript
复制
#!/usr/bin/python
# -*- coding: utf-8 -*-

from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os,sys
import smtplib
import getopt

#使用帮助
def usage():
    print('''Usage: 
    SendMail.py [Options]
    eg. SendMail.py -s "邮件标题" -c "邮件正文" -d "xxx@xxx.com,yyy@yyy.com" --content-file mail_content.txt --attach attachment.log
Options:
    -h/--help 显示此帮助
    -s 邮件标题,例如: -s "这里是邮件标题"
    -c 邮件正文,例如: -c "这里是邮件正文"
    -d 邮件接收地址,例如: -d "xxx@xxx.com,yyy@yyy.com"
    --content-file 包含邮件正文的文件,例如: --content-file mail_content.txt
    --attach 附件,可以是绝对或相对路径,例如: --attach attachment.log 或者 --attach /var/log/attachment.log
    Ps:目前此脚本只支持一个附件,暂无发送多个附件的需求
''')

#参数解析
def argParse():
    subject,content,destAddr,content_file,attachment=None,None,None,None,None
    '''
    如果参数很多,可以选择用argparse模块,getopt模块只适用于轻量级的工具。
    getopt(args, shortopts, longopts = [])
    shortopts表示短项参数,longopts表示长项参数,前者使用'-'后者使用'--',需要后接具体参数的短项参数后需要加冒号':'标识,longopts则必须以=结尾,赋值时写不写等号无所谓因为默认是模糊匹配的。
    getopt的返回值分两部分,第一部分是所有配置项和其值的list,类似[(opt1,val1),(opt2,val2),...],第二部分是未知的多余参数,我们只需要在第一部分的list取参数即可。
    第二部分一般无需关注,因为我们会使用getopt.GetoptError直接过滤掉这些参数(即直接报option xxx not recognized)。
    '''
    try:
        sopts, lopts = getopt.getopt(sys.argv[1:],"hs:c:d:",["help","content-file=","attach="])
    except getopt.GetoptError as e:
	    print("GetoptError:")
	    print(e)
        sys.exit(-1)
    for opt,arg in sopts:
	    if opt == '-s':
	        subject=arg
	    elif opt == '-c':
	        content=arg
	    elif opt == '-d':
	        destAddr=arg
	    elif opt == '--attach':
	        attachment=arg
	    elif opt == '--content-file':
	        content_file=arg
	    elif opt == '--attach':
	        attachment=arg
	    else:
	        usage()
	        sys.exit(-1)
    #subject,destAddr必须不能为空
    if not subject or not destAddr:
	    usage()
	    print("Error: subject and destination must not be null!")
	    sys.exit(-1)
    #处理正文文件,如果存在正文文件,那么忽略-c参数,以文件内容为邮件正文
    if content_file and os.path.exists(content_file):
	    try:
	        with open(content_file) as f1:
	            content=f1.read()
	    except:
	        print("Can't open or read the content file!")
	        exit(-1)
    else:
	    pass
    return {'s':subject,'c':content,'d':destAddr,'a':attachment,}

#发送邮件
def main():	
    opts=argParse()
    subject,content,dest,attach=opts['s'],opts['c'],opts['d'],opts['a']
    #通用第三方smtp服务器账号密码
    smtp_server = 'smtp.163.com'
    from_addr = '你的163发件箱'
    password = '你的163发件箱密码'
    to_addr = list(dest.split(","))

    msg = MIMEMultipart()
    msg['From'] = from_addr
    msg['To'] = ','.join(to_addr)
    msg['Subject'] = subject
    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    #处理附件
    if attach and os.path.exists(attach):
	    try:
	        with open(attach) as f2:
		        mime=f2.read()
		        #目前懒的再写多个附件了,因此只支持一个附件
		        attach1=MIMEApplication(mime)
		        attach1.add_header('Content-Disposition','attachment',filename=attach)
		        msg.attach(attach1)
	    except:
	        print("Can't open or read the attach file!")
	        exit(-1)
    else:
	    pass

    server = smtplib.SMTP_SSL(smtp_server, 465)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, to_addr, msg.as_string())
    server.quit()

if __name__=='__main__':
    main()

三、更改权限后就可以在安装了python的服务器上发送邮件啦(一般服务器都自带python2版本)。

例如:

代码语言:javascript
复制
[root@python leo]# chmod 755 SendMail.py
[root@python leo]# ./SendMail.py -s "邮件标题" -c "邮件正文" -d "xxx@qq.com" --content-file mail.txt 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档