您的位置:首页 > 编程语言 > Python开发

使用Python发送带附件的邮件

2016-01-19 13:41 771 查看

    做运维值班时,每天早上都要通过邮箱发送日报,最近开始学习Python,这下可以让电脑自己去发邮件了!

    初学Python,相关代码可能不够完善,使用的是python 3.5版本。

    实际遇到最大的问题就是使用网页版邮箱时,附件是中文时会导致乱码的问题,网上查了查有好多不同的版本,经过验证总结,总算在我这个环境上(Win10+IE11)通过了。

   

    首先要读取配置文件  ----  GetMailConfig.py:

#! /usr/bin/python

MailConfig = open('mailconfig.ini')

Server = MailConfig.readline()
Server = Server[(Server.find(':') + 1):]
Server = Server.rstrip()

Port = MailConfig.readline()
Port = Port[(Port.find(':') + 1):]
Port = Port.rstrip()

From = MailConfig.readline()
From = From[(From.find(':') + 1):]
From = From.rstrip()

Password = MailConfig.readline()
Password = Password[(Password.find(':') + 1):]
Password = Password.rstrip()

ToList = MailConfig.readline()
ToList = ToList.rstrip()
ToList = ToList[(ToList.find(':') + 1):]
ToList = ToList.split(';')

MailConfig.close()

    mailconfig.ini的内容如下:

ServerName:smtp.qq.com
ServerPort:25
From:12345678@qq.com
Password:87654321
To:333333@163.com;4444444@qq.com //多个收件人用;隔开

    操作失败时希望程序能记录一下操作失败了,因此创建了  RecordLog.py:

#! /usr/bin/python
import time
import platform

#记录日志函数(日志文件名,记录的信息)
def FuncRecordLog(logName , logMsg):
sysStr = platform.system()
if(sysStr == "Linux"):
logName = "Log/" + logName + ".log"
else:
logName = "Log\\" + logName + ".log"
logMsg = time.asctime() + ":      " + logMsg + "\n"
fileWrite = open(logName , "a")
fileWrite.write(logMsg)
fileWrite.close()

    最后就是发送邮件了  SendMail.py:

#! /usr/bin/python
#coding: utf-8
import smtplib
import string
import GetMailConfig
import RecordLog
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

SUBJECT = '运维故障日报'
TO = ','.join(GetMailConfig.ToList)
msg = MIMEMultipart('related')
msgtext = MIMEText('<font color=red>运维故障日报,详细情况见附件.</font>','html','utf-8')
msg.attach(msgtext)
attach = MIMEText(open('运维故障日报.xlsx','rb').read(),'base64','utf-8')
attach['Content-Type'] = 'application/octet-stream'
attach.add_header('Content-Disposition', 'attachment',filename=('gbk', '','运维故障日报.xlsx'))
msg.attach(attach)
msg['Subject'] = SUBJECT
msg['From'] = GetMailConfig.From
msg['To'] = TO

#使用qq邮箱时确保邮箱开启了POP3/SMTP服务......
try:
server = smtplib.SMTP(GetMailConfig.Server,int(GetMailConfig.Port))
server.login(GetMailConfig.From,GetMailConfig.Password)
server.sendmail(GetMailConfig.From,GetMailConfig.ToList,msg.as_string())
server.quit()
except:
RecordLog.FuncRecordLog("MailOptError" , "发送运维故障日报失败")





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 邮件 乱码