Python 自动发送邮件:可以使用的代码如下

参考代码:

# -*- coding: utf-8 -*-
"""
HaoMiaoWuXian"""import osimport numpy as np
import pandas as pd
import matplotlib.pyplot as pltimport matplotlib as mplimport smtplib
from email.message import EmailMessage
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication# --------------------------Part 0 set initial parameter-------------------------------------------------
mail_user = None            # 邮箱登录名
mail_pass = None            # 邮箱授权码,可百度如何获取sender    = None            # 发件人
receivers = None            # 收件人列表,list形式
chaosong  = None            # 抄送人列表,list形式
# --------------------------------------------------------------------------------------------------------
infoStr = {"bodeText":None,"data_link":None,"ImageInfo":[],"AttachFiles":[],           #需要的全局变量"Table_Data":None}
msg = []def Init_Private_Message():            #自己的私人信息,要在这里填写global mail_userglobal mail_passglobal senderglobal receiversglobal chaosongmail_user = ''               # 邮箱登录名mail_pass = ''               # 邮箱授权码,可百度如何获取sender    = ''               # 发件人receivers = ['']             # 收件人列表,list形式chaosong  = ['']             # 抄送人列表,list形式mpl.rcParams['font.sans-serif'] = ['KaiTi']     # 设置要使用字体mpl.rcParams['font.serif'] = ['KaiTi']mpl.rcParams['axes.unicode_minus'] = False      # 使 - 号显示os.chdir(r'D:\code') # 设置文件路径def Set_mail_Para(subject):# 设置邮件体对象global msgmsg = MIMEMultipart()                         # 邮件体对象,此处可加入参数, 具体可百度#subject = 'python send email test'           # 邮件主题msg['subject'] = Header(subject, 'utf-8')     # 加入邮件主题msg['From'] = "{}".format(sender)             # 加入邮件发送人msg['To'] = ",".join(receivers)               # 加入邮件接收人msg['Cc'] = ",".join(chaosong)                # 加入邮件抄送人,如无,可注释掉def Process_Excel_Data_Need():          #用户可以自己定义要处理的是什么df = pd.read_excel('零售总额.xlsx', sheet_name = 'Sheet1')df['年'] = df['统计时间'].apply(lambda x: x[:5])#print(df['年'])#print(len(df))# 图片df_x = np.arange(len(df)); df_real_x = df['统计时间']; df_y = df['社会消费品零售总额(亿元)']fig = plt.figure(figsize=(10,6))plt.plot(df_x, df_y ,  label="社会消费品零售总额(亿元)_label")xticks = np.arange(0,len(df_x)+1,12)#start,stop,stepxlabels = [df_real_x[x] for x in xticks[:-1]]+list(df_real_x)[-1:]#print(xticks)#print(xlabels)plt.xticks(xticks, xlabels)plt.legend(loc = 'upper left')fig.autofmt_xdate()plt.savefig("data_image.jpg")# 表格df_count = df.groupby('年', as_index=False)['统计时间','社会消费品零售总额(亿元)'].agg({'统计时间':len, '社会消费品零售总额(亿元)':sum})df_count['统计时间'] = df_count['统计时间']df_count.rename(columns = {'统计时间':'统计总月份数', '社会消费品零售总额(亿元)':'每年零售总额(亿元)'}, inplace=True)return df_countdef Process_DataInfo_MaiNeed():         #用户可以自己定义要放置什么资源global infoStrbodyText = "This is a text mail by me!"infoStr["bodeText"] = bodyTextdata_link = 'https://blog.csdn.net/u012417290/article/details/77858531?spm=1001.2014.3001.5501'infoStr["data_link"]=data_linkinfoStr["ImageInfo"] = []imgSource1 = {"imageFile":"chart_1.png","chart_title":"chart_1_data:","imagewidth":720,"imageheight":600}imgSource2 = {"imageFile":"chart_2.png","chart_title":"chart_2_data:","imagewidth":720,"imageheight":600}imgSource3 = {"imageFile":"chart_3.png","chart_title":"chart_3_data:","imagewidth":720,"imageheight":600}imgSource4 = {"imageFile":"data_image.jpg","chart_title":"chart_4_data:","imagewidth":720,"imageheight":600}infoStr["ImageInfo"].append(imgSource1)infoStr["ImageInfo"].append(imgSource2)infoStr["ImageInfo"].append(imgSource3)infoStr["ImageInfo"].append(imgSource4)AttachFiles = ["chart_1.png","chart_2.png","chart_3.png",'零售总额.xlsx']infoStr["AttachFiles"]=AttachFilesdef Init_mail_text_Body(infoStr):HeadTmp = """\
<html><head></head><body><pre style="font-family:arial">Dears,{bodeText}所用数据链接:<a href="{link}">Click</a>.</pre>""".format(bodeText = infoStr["bodeText"],link=infoStr["data_link"])imgTemp = ""imageHtml = ""imageNum = len(infoStr["ImageInfo"])for i in range(imageNum):imgTemp = """\<p>{chart_title}<br /><img src="cid:{imageIdx}", width={imagewidth}, height={imageheight}  ></p>""".format(imageIdx=str(i),chart_title=infoStr["ImageInfo"][i]["chart_title"],  imagewidth=infoStr["ImageInfo"][i]["imagewidth"],imageheight=infoStr["ImageInfo"][i]["imageheight"])imageHtml = imageHtml + imgTempleftBody = """\</body>
</html>"""htmlFile = HeadTmp + imageHtml + leftBodyhtmlApart = MIMEText(htmlFile, 'html')for i in range(imageNum):imageFile = infoStr["ImageInfo"][i]["imageFile"]imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])idexStr = '<'+str(i)+'>'imageApart.add_header('Content-ID', idexStr)msg.attach(imageApart)msg.attach(htmlApart)def Mail_Add_AttachFile(infoStr):# 加入多个附件files = infoStr["AttachFiles"]for i in np.arange(len(files)):attFile = MIMEApplication(open(files[i], 'rb').read())attFile.add_header('Content-Disposition', 'attachment', filename=files[i])msg.attach(attFile)def get_html_msg(df_s, table_title):"""1. 构造html信息"""df_html = df_s.to_html(escape=False)# 表格格式head = \"""<head><meta charset="utf-8"><STYLE TYPE="text/css" MEDIA=screen>table.dataframe {border-collapse: collapse;border: 2px solid #a19da2;/*默认居中auto显示整个表格*/margin: left;}table.dataframe thead {border: 2px solid #91c6e1;background: #f1f1f1;padding: 10px 10px 10px 10px;color: #333333;}table.dataframe tbody {border: 2px solid #91c6e1;padding: 10px 10px 10px 10px;}table.dataframe tr {}table.dataframe th {vertical-align: top;font-size: 14px;padding: 10px 10px 10px 10px;color: #105de3;font-family: arial;text-align: center;}table.dataframe td {text-align: left;padding: 10px 10px 10px 10px;}body {font-family: 宋体;}h1 {color: #5db446}div.header h2 {color: #0002e3;font-family: 黑体;}div.content h2 {text-align: center;font-size: 28px;text-shadow: 2px 2px 1px #de4040;color: #fff;font-weight: bold;background-color: #008eb7;line-height: 1.5;margin: 20px 0;box-shadow: 10px 10px 5px #888888;border-radius: 5px;}h3 {font-size: 22px;background-color: rgba(0, 2, 227, 0.71);text-shadow: 2px 2px 1px #de4040;color: rgba(239, 241, 234, 0.99);line-height: 1.5;}h4 {color: #e10092;font-family: 楷体;font-size: 20px;text-align: center;}td img {/*width: 60px;*/max-width: 300px;max-height: 300px;}</STYLE></head>"""# 构造正文表格body = \"""<body><div align="center" class="header"><!--标题部分的信息--><!--<h1 align="left">{table_title}</h1>--><p align="left">{table_title}</p></div><div class="content">{df_html}</div></body><br /><br />""".format(df_html=df_html, table_title=table_title)html_msg= "<html>" + head + body + "</html>"
#    这里是将HTML文件输出,作为测试的时候,查看格式用的,正式脚本中可以注释掉
#    fout = open('test.html', 'w', encoding='UTF-8', newline='')
#    fout.write(html_msg)return html_msgdef Mail_Constrct_Table(df_count, table_title):# html 内容html_msg = get_html_msg(df_count, table_title)content_html = MIMEText(html_msg, "html", "utf-8")msg.attach(content_html) def Sent_Mail():sftp_obj = smtplib.SMTP_SSL(host='smtp.163.com', port = 994)sftp_obj.login(mail_user, mail_pass)sftp_obj.sendmail(sender, receivers, msg.as_string())sftp_obj.quit()sftp_obj.close()print('\n'  + '__The email has been sent successfully')Init_Private_Message()
Set_mail_Para("Mail_Subject__1")
df_count = Process_Excel_Data_Need()
Process_DataInfo_MaiNeed()
Init_mail_text_Body(infoStr)
Mail_Add_AttachFile(infoStr)
Mail_Constrct_Table(df_count,"table_example")
Sent_Mail()

Python 自动发送邮件相关推荐

  1. python自动发送邮件不需要发件邮箱_python使用QQ邮箱实现自动发送邮件

    最近用到Python自动发送邮件,主要就是三步,登录邮件.写邮件内容.发送,用到的库是 smtplib 和 email,直接使用pip安装即可 我使用的是QQ邮箱,首先需要设置QQ邮箱POP3/SMT ...

  2. python自动发送邮件_Python自动发送邮件

    用 Python 自动发送邮件在日常工作中可以避免一些重复性的工作,Python 用来发送邮件会涉及到 smtplib 和 Email 两个模块,smtplib 是用来发送邮件用的,Email 是用来 ...

  3. Python 自动发送邮件详细教程

    自动发送邮件能应用于许多场景中,比如我想要知道股票策略中的股票池是否有实时的更新,这时候如果再拉一遍数据,跑一遍脚本,实在是太浪费时间了.为什么不把这一套流程放到服务器上,然后到点自动运行并发送邮件呢 ...

  4. csdn最牛最全的使用python自动发送邮件

    使用python自动发送邮件 1.Python 自带的发送邮件功能 在生成报告后我们希望框架能自动把报告发送到我们的邮箱中.和outlook,foxmail等邮件客户端一样,Python中发送邮件需要 ...

  5. python自动发送邮件

    python自动发送邮件 1.导入yagmail pip install yagmail #如果上面方式报错,建议使用阿里云镜像进行添加 pip install yagmail -i https:// ...

  6. 高效办公,如何利用Python自动发送邮件

    自动发送邮件 我们把报表做出来以后一般都是需要发给别人查看,对于一些每天需要发的报表或者是需要一次发送多份的报表,这个时候可以考虑借助Python来自动发送邮件. 使用邮箱的第一步 一般我们在使用QQ ...

  7. python自动发送邮件脚本

    目录 需要开通smtp功能 脚本 需要开通smtp功能 这里举例子使用的163的邮箱,每个邮箱都是一样的,发件邮箱设置即可 163网易免费邮-你的专业电子邮局 脚本 # -*- coding:utf- ...

  8. python自动发送邮件实现

    目录 1 前言 2 准备工作 2.1 电子邮件的基础知识. 2.2 python邮件库 2.3 邮箱设置 3 python实现邮件自动发送 3.1 SMTP()和send()方法介绍 3.2 pyth ...

  9. Python 自动发送邮件实战案例,人人都可以学会

    自动发送邮件能应用于许多场景,比如我想要知道股票策略中的股票池是否有实时的更新,这时候如果再拉一遍数据,跑一遍脚本,实在是太浪费时间了.为什么不把这一套流程放到服务器上,然后到点自动运行并发送邮件呢? ...

  10. python自动发送邮件(html、附件等),qq邮箱和网易邮箱发送和回复

    在python中,我们可以用程序来实现向别人的邮箱自动发送一封邮件,甚至可以定时,如每天8点钟准时给某人发送一封邮件.今天,我们就来学习一下,如何向qq邮箱,网易邮箱等发送邮件. 一.获取邮箱的SMT ...

最新文章

  1. linux安装8168网卡,Fedora 配置 RTL8168/8111 网卡 Linux下 RTL8168/8111 网卡配置
  2. 【文本分类】Attention-Based Bidirectional Long Short-Term Memory Networks for Relation Classification
  3. android-XML解析Dom,Sax,Pull
  4. Spring Session - 源码解读
  5. python日志文件保存在哪里,Python日志记录-检查日志文件的位置?
  6. 神策数据成林松:数据智能在业务场景下的应用(附 PPT 下载)
  7. leetcode 575. 分糖果(Java版)
  8. 20 万台 QQ 服务器全面上云!
  9. kettle 连接 Oracle 异常
  10. python中seaborn库_GitHub - a13544835729/python-seaborn: python seaborn库基础用法
  11. JS内置对象方法——array
  12. java官方编译器_JAVA 编译器
  13. python mro
  14. 中华流传十大吉祥图解
  15. 分块矩阵求逆 matlab,矩阵的分块求逆及解线性方程组.doc
  16. 溴PEG溴,Br-PEG-Br
  17. Xshell远程连接阿里云
  18. 基于WebSocket和Redis实现Bilibili弹幕效果
  19. 红楼梦人物分析系统c语言,红楼梦人物分析.doc
  20. python中的for语句涉及的序列可以是( )-Python for循环语句

热门文章

  1. 中国互联网有哪些黑色产业链?
  2. 支付宝前端团队详解基于Node.js Web框架Chair
  3. 微信公众号开发:素材管理(临时、永久)
  4. 划重点!划重点!2022面试必刷461道大厂架构面试真题汇总+面经+简历模板
  5. 域名生成企业邮箱golang企业邮箱发邮件 golang gmail发邮件
  6. 解决阿里云不能使用yum问题
  7. linux数字版权管理,数字版权管理系统 DRM
  8. 行星月球科学探索成绩斐然 桌面实验或可理解黑洞性质
  9. 可汗学院公开课:统计学笔记——假设检验
  10. 计算机重装系统桌面文件如何恢复,电脑重装系统后桌面文件如何恢复-万兴恢复专家...