zoukankan      html  css  js  c++  java
  • Python 在Linux上用Python脚本发送邮件

    下面是一个完整的在Linux系统上 用Python 写好的发送邮件的脚本,可以直接使用,

    是从网上搜索过来的, 忘记是从哪位高人哪里找到的, 吃水不忘挖井人,非常感谢那位高人,

    转记在自己的博客园里,发扬光大,再次感谢那位高人。

    备注1:注册一个163邮箱

    备注2: 修改一下脚本里面的  from_addr  和password  ,本人亲测有效。

              from_addr = 'AAAA@163.com' #输入你的163邮箱
              password = 'BBBBBBBBBB' #输入163邮箱的客户端授权密码,需要到163邮箱里面去设置获得

    源代码如下:

    #!/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 = 'AAAA@163.com' # 输入你的163邮箱
    password = 'BBBBBBBBBB' # 输入163邮箱的客户端授权密码,需要到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) # 如果使用的25端口的非加密通道,那么使用SMTP方法替换SMTP_SSL
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, to_addr, msg.as_string())
    server.quit()


    if __name__ == '__main__':
    main()


    
    
  • 相关阅读:
    MySQL之字符集
    PHP7.0-PHP7.3新特性与变更
    MySQL之开发规范
    php框架之thinkphp
    MySQL之日期时间类型
    php扩展之Yar
    XAMPP支持多PHP版本
    MySQL之执行流程
    RabbitMQ之php-amqplib使用
    (转)YAML最最基础语法
  • 原文地址:https://www.cnblogs.com/tonyxiao/p/15347279.html
Copyright © 2011-2022 走看看