使用Python发送带附件的邮件



    做运维值班时,每天早上都要通过邮箱发送日报,最近开始学习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" , "发送运维故障日报失败")








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值