#!/usr/bin/env python
# -*- coding:utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header
import datetime
import os.path
import createsheet
import base64
import sys
reload(sys)
sys.setdefaultencoding('utf8')
oct21st=datetime.datetime.now()
nowday=oct21st.strftime('%Y-%m-%d')
class Mailer(object):
def __init__(self,maillist,mailtitle,mailcontent):
self.mail_list = maillist
self.mail_title = mailtitle
self.mail_content = mailcontent
# self.mail_host = "smtp.163.com"
# self.mail_user = "*"
# self.mail_pass = "*"
# self.mail_postfix = "*"
self.mail_host = "smtp.exmail.qq.com"
self.mail_user = "*"
self.mail_pass = "*"
self.mail_postfix = "*"
def sendMail(self):
#创建一个带附件的实例
#加邮件头,设置根容器属性
## 构造MIMEMultipart对象做为根容器
me = self.mail_user + "<" + self.mail_user+">"
msg = MIMEMultipart()
msg['Subject'] = Header(self.mail_title, 'utf-8')
msg['From'] = me
msg['To'] = ";".join(self.mail_list)
#添加邮件内容
#注意,要指定邮件内容的编码为utf-8,否则中文会有乱码
#构造MIMEText对象做为邮件显示内容并附加到根容器
#puretext = MIMEText('<h1>你好,<br/>'+self.mail_content+'</h1>','html','utf-8')
puretext = MIMEText('Hi: 见附件','plain','utf-8')
msg.attach(puretext)
# jpg类型的附件
# jpgpart = MIMEApplication(open('/home/mypan/1949777163775279642.jpg', 'rb').read())
# jpgpart.add_header('Content-Disposition', 'attachment', filename='beauty.jpg')
# msg.attach(jpgpart)
# 首先是xlsx类型的附件
# 设置附件头
xlsxname='C:UsersAdministratorDesktop内容* '+nowday+'.xlsx'
# filename=os.path.basename(xlsxname).encode('gb2312')
filename=os.path.basename(xlsxname)
xlsxpart = MIMEApplication(open(xlsxname.decode('utf-8'), 'rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='=?utf-8?b?'+base64.b64encode(filename.encode('utf-8'))+'?=')
msg.attach(xlsxpart)
# mp3类型的附件
#mp3part = MIMEApplication(open('kenny.mp3', 'rb').read())
#mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3')
#msg.attach(mp3part)
# pdf类型附件
#part = MIMEApplication(open('foo.pdf', 'rb').read())
#part.add_header('Content-Disposition', 'attachment', filename="foo.pdf")
#msg.attach(part)
try:
s = smtplib.SMTP() #创建邮件服务器对象
s.connect(self.mail_host) #连接到指定的smtp服务器。参数分别表示smpt主机和端口
s.login(self.mail_user, self.mail_pass) #登录到你邮箱
s.sendmail(me, self.mail_list, msg.as_string()) #发送内容
s.close()
return True
except Exception, e:
print str(e)
return False
def send_mail():
createsheet.createsheet()
mailto_list = ["*"]
mail_title = '你好'
mail_content = 'Hey this is content'
mm = Mailer(mailto_list,mail_title,mail_content)
res = mm.sendMail()
print res
if __name__ == '__main__':
#send list
send_mail()