sendmail --续(发送文件和图片)

Posted zhan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 

 

登录邮箱查收邮件:

 

 

 

以上是关于sendmail --续(发送文件和图片)的主要内容,如果未能解决你的问题,请参考以下文章

续Gulp使用入门三步压缩图片

sendmail 如何发送附件

使用命令行和 sendmail 发送带有多个附件的电子邮件

Laravel/XAMPP/Sendmail 不发送邮件

dokuwiki 配置 sendmail 邮件发送

如何使用 perl 和 sendmail 从 URL 发送 pdf [Mail::Sendmail]