使用python调用email模块发送邮件附件

使用python调用email模块实现附件发送

需要模块:

import datetime
import time
import sys
import mimetypes 
import smtplib
import email.MIMEMultipart  
import email.MIMEText  
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.Utils import COMMASPACE, formatdate
from email.mime.image import MIMEImage

模块安装:
模块安装:

系统默认应该都已安装这些模块,如有确认请自行安装;
pip install 模块名

脚本内容:

[root@baolin shell]# cat py_sendmail.py
#!/bin/env python
# -*- encoding: utf-8 -*-
#-------------------------------------------------------------------------------
# Purpose: 附件发送
# by baolin
#-------------------------------------------------------------------------------
import datetime
import time
import sys
import mimetypes 
import smtplib
import email.MIMEMultipart  
import email.MIMEText  
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.Utils import COMMASPACE, formatdate
from email.mime.image import MIMEImage

reload(sys)
sys.setdefaultencoding('utf8')

#获取前一天日期
#month = (datetime.date.today() - datetime.timedelta(days=15)).strftime("%m")
now_time = datetime.datetime.now()                          # 获取当前时间
yes_time = now_time + datetime.timedelta(days=-1)           # 当前时间 -1
month = yes_time.strftime('%Y-%m-%d')                       # 截取时间日期部分
 
msg=MIMEMultipart()

#发邮箱
msg["From"] = "[email protected]"

#收件箱地址,可以为多个
Tolist = ['[email protected]','[email protected]',]

#邮件标题
msg["Subject"] = '%s日报统计信息' %month

#邮件内部内容文字
text=MIMEText(("附件内容为 %s日报信息,详情请见附件。")% month,_charset='utf-8')
msg.attach(text)

#附件名由外部传入
file_name = sys.argv[1]
print(file_name)
ctype,encoding = mimetypes.guess_type(file_name)
if ctype is None or encoding is not None:
     ctype = 'application/octet-stream'
maintype,subtype = ctype.split('/',1)  

att = MIMEImage(open(file_name, 'rb').read(),subtype)
print ctype,encoding
att["Content-Disposition"] = 'attachmemt;filename="%s"' %file_name
msg.attach(att)

# 发件箱的服务器,发件箱用户密码
smtp = smtplib.SMTP()
smtp.connect("smtp.gmail.com")
smtp.starttls()
smtp.login("[email protected]","*********")

smtp.sendmail(msg["From"],Tolist,msg.as_string())
smtp.close()

运行方式:

# 附件名如是中文,会出现乱码问题
[root@baolin shell]#python py_sendmail.py file_name

内容参考:

http://blog.csdn.net/zm2714/article/details/7993732
http://www.cnblogs.com/zhoujinyi/archive/2013/05/07/3065151.html

转载于:https://www.cnblogs.com/baolin2200/p/7793754.html

你可能感兴趣的:(使用python调用email模块发送邮件附件)