记录一下Python 发送邮件的代码,这是半年前写的,不知道现在有什么类库的改动。

类库

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import datetime
 
  1. def SendEmail(self,SendEmailExcelUrl,ProjectName):
  2.  
  3. sender ='发送人邮箱'
  4. senderPwd =os.environ.get('EmailPassword') #邮箱密码我这里是放在环境变量中了(Win)
  5. receivers ='123@123.com,123@123.com' #接收人邮箱
  6. #create a Instance
  7. message = MIMEMultipart()
  8. message['From'] = Header("发送人", 'utf-8')
  9. message['To'] = Header("邮件内容标题", 'utf-8')
  10. subject = '邮件标题’
  11. message['Subject'] = Header(subject, 'utf-8')
  12. #Message body content
  13. message.attach(MIMEText(' Dear All, \n\n ××× \n\n Regards, \n ××××××× ', 'plain', 'utf-8'))
  14. #Send xlsx file
  15. att = MIMEText(open(SendEmailExcelUrl, 'rb').read(), 'base64', 'utf-8')
  16. att["Content-Type"] = 'application/octet-stream'
  17. #Here you can rename the attachments in the message.
  18. att["Content-Disposition"] = 'attachment; filename="{}.xlsx"'.format(ProjectName)
  19. message.attach(att)
  20. try:
  21. smtpObj = smtplib.SMTP('代理服务器地址','代理服务器端口')
  22. smtpObj.starttls()
  23. smtpObj.login(sender, senderPwd)#代理服务器帐号密码验证
  24. smtpObj.sendmail(sender, receivers, message.as_string())
  25. #terminating the session
  26. smtpObj.quit()
  27. print("Send email successful")
  28. except smtplib.SMTPException as e:
  29. print(e.__doc__,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  30. print(e.__context__,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

下面是编辑excel 仅仅用于记录

  python编辑excel 还是比较坑的,个人观点。但是我是调用一个接口,该接口返回excel,该excel的样式什么的都有,如果我直接进行保存这样没问题,但是我需要对其加一列然后在保存excel就被破坏了,后来了解到目前该类库对样式的编辑支持的还不是很好

import xlrd
import xlwt
from openpyxl import Workbook ,load_workbook
  1. def CreateCoreExcel(self,SendEmailExcelUrl,ApiSaveExcelSaveUrl):
  2. projectConfigJson=self.getProductfigJson()['Core']
  3. Group= projectConfigJson['Group']
  4. wb = load_workbook(ApiSaveExcelSaveUrl)
  5. ws = wb['Vulnerabilities']
  6. ws.insert_cols(2)
  7. ws.insert_cols(3)
  8. for index, row in enumerate(ws.rows):
  9. if index == 0:
  10. row[1].value='Group'
  11. row[2].value='ServiceName'
  12. else:
  13. values= row[22].value
  14. validationValues=True
  15. try:
  16. values.split('\\')
  17. except Exception as e:
  18. print(e.__doc__,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  19. print(e.__context__,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  20. validationValues=False
  21. print("values not is path values:{}, datetime:{} ".format(values,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
  22. if validationValues == True:
  23. strlist = values.split('\\')
  24. serviceName=strlist[3]
  25. groupName=""
  26. if serviceName in Group['1']:
  27. groupName="1"
  28. elif serviceName in Group['2']:
  29. groupName="2"
  30. elif serviceName in Group['3']:
  31. groupName="3"
  32. else:
  33. groupName="OtherGroup"
  34. row[1].value=groupName
  35. row[2].value=serviceName
  36. else :
  37. row[1].value="N/A"
  38. row[2].value="N/A"
  39. content = []
  40. index = 1
  41. for i in range(2,ws.max_row+2):
  42. contentJson ={}
  43. for j in range(1,ws.max_column+1):
  44. contentJson[ws.cell(index,j).value]=ws.cell(i,j).value
  45. content.append(contentJson)
  46. jsonstr=json.dumps(content)
  47.  
  48. wbnew = Workbook()
  49. sheet = wbnew.active
  50. listHead=[]
  51. data= json.loads(jsonstr)
  52. for c,i in enumerate(data[0].keys()):
  53. sheet.cell(row=1,column=c+1,value=i)
  54. listHead.append(i)
  55. for r,i in enumerate(data):
  56. row=r+2
  57. for c,d in enumerate(listHead):
  58. sheet.cell(row=row,column=c+1,value=i.get(d,""))
  59. returnValue=os.path.exists(SendEmailExcelUrl)
  60. if returnValue==True:
  61. os.remove(SendEmailExcelUrl)
  62. wbnew.save(SendEmailExcelUrl)

  该内容只是个人记录。

Python 发送邮件 and 编辑Excel的更多相关文章

  1. python接口自动化(三十二)--Python发送邮件(常见四种邮件内容)番外篇——上(详解)

    简介 本篇文章与前边没有多大关联,就是对前边有关发邮件的总结和梳理.在写脚本时,放到后台运行,想知道执行情况,会通过邮件.SMS(短信).飞信.微信等方式通知管理员,用的最多的是邮件.在linux下, ...

  2. Python导出数据到Excel表格-NotImplementedError: formatting_info=True not yet implemented

    在使用Python写入数据到Excel表格中时出现报错信息记录:“NotImplementedError: formatting_info=True not yet implemented” 报错分析 ...

  3. Python自动化测试发送邮件太麻烦?!一起聊一聊 Python 发送邮件的3种方式

    1. 前言 发送邮件,我们在平时工作中经用到,做为测试人员,在自动化测试中用的也比较多,需要发送邮件给某领导 SMTP是Python默认的邮件模块,可以发送纯文本.富文本.HTML 等格式的邮件 今天 ...

  4. python发送邮件

    python发送邮件(无附件) ======================================================= #!/usr/bin/env python#coding ...

  5. python发送邮件及附件

    今天给大伙说说python发送邮件,官方的多余的话自己去百度好了,还有一大堆文档说实话不到万不得已的时候一般人都不会去看,回归主题: 本人是mac如果没有按照依赖模块的请按照下面的截图安装 导入模块如 ...

  6. python 发送邮件实例

    留言板回复作者邮件提醒 -----------2016-5-11 15:03:58-- source:python发送邮件实例

  7. 解读Python发送邮件

    解读Python发送邮件 Python发送邮件需要smtplib和email两个模块.也正是由于我们在实际工作中可以导入这些模块,才使得处理工作中的任务变得更加的简单.今天,就来好好学习一下使用Pyt ...

  8. python 发送邮件例子

    想到用python发送邮件 主要是服务器 有时候会产生coredump文件  ,然后因为脚本重启原因,服务器coredump产生后会重启 但是没有主动通知开发人员 想了下可以写个脚本一旦产生cored ...

  9. VSTO学习笔记(五)批量编辑Excel 2010 x64

    原文:VSTO学习笔记(五)批量编辑Excel 2010 x64 近期因为工作的需要,经常要批量处理大量的Excel文件,如果纯手工一个个修改,非常的麻烦,于是写了这么一个帮助类,希望能对你有所帮助. ...

随机推荐

  1. element admin中使用nprogress实现页面加载进度条

    主要是知道是nprogress这个组件实现的就可以了,组件的使用方法可参考:https://blog.csdn.net/ltr15036900300/article/details/47321217 ...

  2. 2019-09-09 memcache

    什么是缓存呢???缓存就是存贮数据(使用频繁的数据)的临时地方缓存可以认为是数据的大池子 一.数据缓存这里所说的数据缓存是指数据库查询缓存,每次访问页面的时候,都会先检测相应的缓存数据是否存在,如果不 ...

  3. 大规模定制模式之于MES的三点思考

    大规模定制(Mass Custermization) ,其目标是大规模生产定制化产品,并且在效率.质量(一致性)等指标方面与大规模批量生产等齐. 这是一种理想或者追求,其提出的背景是目前越发普遍的多品 ...

  4. 【转载】Gradle学习 第九章:Groovy快速入门

    转载地址:http://ask.android-studio.org/?/article/17 To build a Groovy project, you use the Groovy plugin ...

  5. 【软件工程第二次作业】个人项目:WordCountPy

    一.GitHub 地址 项目 GitHub 地址为:https://github.com/bytemo/WordCountTool 二.PSP表格 PSP2.1 Personal Software P ...

  6. 适用于Centos6/7,vsftp自动安装脚本

    #!/bin/bash #vsftp install . /etc/rc.d/init.d/functions NUM=`rpm -q centos-release | awk -F '-' '{pr ...

  7. 记一次wsl上的pip3安装失败问题 The following packages were automatically installed and are no longer required:

    转载请注明来源.https://www.cnblogs.com/sogeisetsu/.然后我的CSDNhttps://blog.csdn.net/suyues/article/details/103 ...

  8. Codeforces E. High Load(构造)

    题目描述: High Load time limit per test 2 seconds memory limit per test 512 megabytes input standard inp ...

  9. BeyondCorps

    This repository provides a short description of the BeyondCorp security model and resources for impl ...

  10. python移动目录下所有子目录文件到新的总目录

    python移动目录下所有子目录文件到新的总目录 import os import shutil def file(p):     p=p     z=os.listdir(p)     for i ...