zoukankan      html  css  js  c++  java
  • sendmail --续(发送文件和图片)

    1、通过Python发送文件和图片。实现代码比较多,由于是练习,尽可能复习以前的模块

    脚本目录结构:

    sendmail/
    ├── confmail
    ├── __init__.py
    ├── pic
    │   ├── car1.jpg
    │   ├── car2.jpg
    │   ├── __init__.py
    │   └── meinv1.png
    ├── sendmail.py
    └── txt
        ├── error.log
        ├── index.html
        └── SOS1.xlsx

    主要实现代码:

    confmail
    [mailConf]
    sender = 2578201379@qq.com
    receives = xxxxxxxx@qq.com;xx@163.com
    smtpserver = smtp.qq.com
    password = xxxxxxx
    subject = "错误日志"
    file = txt/index.html,txt/error.log
    image = pic/car1.jpg,pic/car2.jpg,pic/meinv1.png
    context = txt/index.html
    index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
              <a href="http://www.163.com">官网地址更多>></a>
    
              <h3>豪车:</h3><img src="cid:car1">
          <!--<h3>豪车:</h3><img src="cid:car2">
          <h3>美女:</h3><img src="cid:meinv1">-->
    </body> </html>


    sendmail.py


     
    #coding:utf8
    import email
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    from email.mime.multipart import MIMEMultipart
    from email.mime.image import MIMEImage
    from email.mime.application import MIMEApplication

    import os
    import codecs
    import datetime
    from ConfigParser import ConfigParser

    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    from subprocess import Popen,PIPE
    today = datetime.date.today()
    yesterday = today - datetime.timedelta(days=1)
    yesterday=yesterday.strftime('%Y%m%d')

    class mailConfig(ConfigParser):
    def __init__(self,config):
    ConfigParser.__init__(self,allow_no_value=True)
    # super(mailConfig,self).__init__(allow_no_value=True)
    self.config = config
    self.read(self.config)

    def get_options(self):
    res = {}
    options = self.options("mailConf")
    for option in options:
    res[option] = self.get("mailConf",option)
    return res
    class getCmd():
    def get_ip(self):
    cmd = "/sbin/ifconfig |grep 'netmask' |awk '{print $2}'|grep -v '127.0.0.1'"
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
    stdout, stderr = p.communicate()
    return stdout.strip()
    def get_name(self):
    path = "/data1/games/logic"
    self.gameName = "-".join(path.split('/')[3:])
    return self.gameName

    class SendMail():
    def __init__(self,gameName,server_ip,kwargs):
    self.sender = kwargs['sender']
    self.receives = kwargs['receives']
    self.subject = "{0}({1}) {2}".format(server_ip,gameName,kwargs['subject'])
    self.context = kwargs['context']
    self.smtpserver = kwargs['smtpserver']
    self.password = kwargs['password']
    self.file = list()
    self.image = list()
    self.txt = ""
    for i in kwargs['file'].split(','):
    self.file.append(i.strip())
    for j in kwargs['image'].split(','):
    self.image.append(j.strip())

    def set_content(self):
    self.message = MIMEMultipart('related')
    self.message['From'] = self.sender
    self.message['To'] = self.receives
    self.message['Subject'] = self.subject
    with codecs.open(self.context,'rb') as fd :
    self.txt = fd.read()
    self.message.attach(MIMEText('{0}'.format(self.txt), 'html', 'utf-8'))
    # self.message.attach(MIMEText('{0}'.format(self.context), 'plain', 'utf-8'))

    def set_file(self):
    # list = ["error.log","SOS1.xlsx"]
    for file in self.file:
    with codecs.open(file,'rb') as fd:
    att = MIMEText(fd.read(),_subtype="html")
    file_name = file.split('/')[1].strip()
    att["Content-Type"] = 'application/octet-stream'
    att.add_header('Content-Disposition','attachment', filename=("utf-8", "", file_name))
    self.message.attach(att)

    def set_pic(self):
    for img in self.image:
    filename = img.split('/')[1].split('.')[0]
    print("filename is {0}".format(filename))
    with codecs.open(img,'rb') as fd :
    attrImage = MIMEImage(fd.read())
    # attrImage.add_header('Content-Disposition','attachment', filename=("utf-8", "", file))
    attrImage.add_header("Content-ID", "<{0}>".format(filename))
    self.message.attach(attrImage)

    def sendmails(self):
    server = smtplib.SMTP_SSL()
    server.connect(self.smtpserver, '465')
    # server.set_debuglevel(1)
    server.login(self.sender, self.password)
    server.sendmail(self.sender, self.receives, self.message.as_string())
    server.quit()
    def main():
    mc = mailConfig("confmail")
    options = mc.get_options()
    cmdResu = getCmd()
    server_ip = cmdResu.get_ip()
    gameName = cmdResu.get_name()
    sendMail = SendMail(server_ip,gameName,options)
    sendMail.set_content()
    sendMail.set_file()
    sendMail.set_pic()
    sendMail.sendmails()

    if __name__ == "__main__":
    main()
    
    

    执行结果:

    python sendmail.py 

    登录邮箱查收邮件:

     
  • 相关阅读:
    vi 整行 多行 复制与粘贴
    FPGA设计—UVM验证篇 Hello world
    武汉市最大的二手车市场
    vim 使用技巧
    CentOS 7下的软件安装方法及策略
    搜索插件:ack.vim
    Vim插件管理
    【一】 sched.h
    Android USB驱动源码分析(-)
    在Python中反向遍历序列(列表、字符串、元组等)的五种方式
  • 原文地址:https://www.cnblogs.com/pythonlx/p/8278499.html
Copyright © 2011-2022 走看看