参照
python批量发送邮件--包括批量不同附件_xiaozhou的博客-CSDN博客_python批量发送邮件
1 设计要点小猪在公司做出纳,干的活却包括了出纳、会计、结算专员等工作,周末都要被无奈在家加班,主要还没有加班费,简直是被公司严重压榨。每个月初都要给每个工长发预付款账单邮件,月中发结算款账单。重复性机械工作。 一个及格线上的程序员,最起码的觉悟就是将重复性的机械工作自动化,于是,在我花了一个多小时,帮她给一部分工长发了一次邮箱后,默默的回来写了这个脚本。 所以,设计要点就是一个字——...
https://blog.csdn.net/qq_41059320/article/details/82754577
这个学习发不同附件给不同用户,怎么实现BatchsEmailSender.py中输出的邮件发送记录信息,显示在发送邮件1.py中的邮件发送状态:self.info1_text这个组件中呢?
BatchsEmailSender.py代码如下:
import os
import sys
import importlib
importlib.reload(sys)
import csv
import smtplib
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from email import encoders
import msvcrt
import time
# ===================批量发送邮件测试(二)----邮件内容固定,主题和附件变化=========
# --------------------发送服务器配置---------------
# sender_host = 'smtp.163.com:25' # 默认服务器地址及端口
sender_host = 'smtp.163.com' # 使用SSL连接,
sender_user = 'cns@163.com'
sender_pwd = 'CKOR'
sender_name = u'IT'
# self.attach_type = ".xlsx"
# --------------根据输入的CSV文件,获取通讯录人名和相应的邮箱地址-------
def getAddrBook(addrBook):
'''
@作用:根据输入的CSV文件,形成相应的通讯录字典
@返回:字典类型,name为人名,value为对应的邮件地址
'''
with open(addrBook,'r',encoding='gbk') as addrFile:
reader = csv.reader(addrFile)
name = []
value = []
for row in reader:
name.append(row[0])
value.append(row[1])
addrs = dict(zip(name, value))
return addrs
# addrs = {name : value}
# -------------------根据附件名称中获得的人名,查找通讯录,找到对应的邮件地址---------------
def getRecvAddr(addrs,person_name):
if not person_name in addrs:
print("没有<"+person_name+">的邮箱地址! 请在联系人中添加此人邮箱后重试。")
print("请按任意键退出程序:")
anykey = ord(msvcrt.getch()) # 此刻捕捉键盘,任意键退出
if anykey in range(0,256):
sys.exit(0)
# try:
return addrs[person_name]
# except KeyError:
# print("通讯录中无此人:"+person_name)
# # raise SystemExit
# --------------------添加附件-----------------------------------
def addAttch(attach_file):
att = MIMEBase('application','octet-stream') # 这两个参数不知道啥意思,二进制流文件
att.set_payload(open(attach_file,'rb').read())
# 此时的附件名称为****.xlsx,截取文件名
att.add_header('Content-Disposition', 'attachment', filename=('gbk','', attach_file.split("\\")[-1]))
encoders.encode_base64(att)
return att
# ---------------------发送邮件-----------------------
def mailSend(attach_path,bookFile,mail_content):
# smtp = smtplib.SMTP() # 新建smtp对象
# smtp.connect(sender_host)
smtp = smtplib.SMTP_SSL(sender_host,994) # 使用SSL连接
smtp.login(sender_user, sender_pwd)
# # attach_path = attach_path
# # mail_content = mail_content
addrBook = bookFile
addrs = getAddrBook(addrBook)
count = 1
for root,dirs,files in os.walk(attach_path):
for attach_file in files: # attach_file : ***_2_***.xlsx
msg = MIMEMultipart('alternative')
att_name = attach_file.split(".")[0]
subject = att_name
msg['Subject'] = subject # 设置邮件主题
person_name = subject.split("_")[-1]
recv_addr = getRecvAddr(addrs,person_name)
msg['From'] = formataddr([sender_name,sender_user]) # 设置发件人名称
# msg['To'] = person_name # 设置收件人名称
msg['To'] = formataddr([person_name,recv_addr]) # 设置收件人名称
# mail_content = getMailContent(content_path)
msg.attach(MIMEText(mail_content)) # 正文 MIMEText(content,'plain','utf-8')
attach_file = root+"\\"+attach_file
att = addAttch(attach_file)
msg.attach(att) # 附件
# 增加判断是否到达最大发送限制
if count >= 10:
smtp.quit()
# print("")
time.sleep(5) # 让子弹飞一会儿
count = 1
smtp = smtplib.SMTP_SSL(sender_host,994) # 使用SSL连接
smtp.login(sender_user, sender_pwd)
smtp.sendmail(sender_user, [recv_addr,], msg.as_string()) # smtp.sendmail(from_addr, to_addrs, msg)
print("已发送: "+person_name+" <"+recv_addr+">")
count += 1
# time.sleep(5) # 163检测,一次连接状态,最多只能发送10封邮件。故加延时,延时5秒也没用
time.sleep(1)
smtp.quit()
#print("请按任意键退出程序:")
anykey = ord(msvcrt.getch()) # 此刻捕捉键盘,任意键退出
if anykey in range(0,256):
#print("Have a nice day !")
time.sleep(1)
sys.exit()
发送邮件1.py代码如下:
```python
# -*- coding:utf-8 -*-
# ==================BatchMailSender V1.3 ===========================
import tkinter
from tkinter.constants import *
from tkinter import *
# from tkinter import ttk
from tkinter.filedialog import askdirectory
from tkinter.filedialog import askopenfilename
from tkinter.scrolledtext import ScrolledText
import tkinter.messagebox
from tkinter import END
import time
import BatchsEmailSender
from BatchsEmailSender import mailSend
class MyGUI():
"""@brief:使用GUI界面来选择邮箱附件所在的文件夹和邮箱通讯录
"""
# 构造函数
def __init__(self,init_window_name):
self.init_window_name = init_window_name
# 初始化窗口
def set_init_window(self):
self.init_window_name.title("批量发送邮件【根据csv读取收件人姓名和邮件地址,然后发送对应名称的文件】 ") # 设置标题
self.init_window_name.geometry('600x480+300+200') # 设置尺寸
self.init_window_name.attributes('-alpha',1) # 属性?
# 设置标签
self.attach_label = Label(self.init_window_name,text="请选择附件所在文件夹:",bg='lightblue')
self.attach_label.place(x=50,y=53-20,width=180,height=30)
self.book_label = Label(self.init_window_name,text="请选择邮箱地址通讯录(CSV文件):",justify='left',bg='lightblue')
self.book_label.place(x=50,y=125-20,width=180,height=30)
self.info_label = Label(self.init_window_name,text="请输入邮件正文内容:",bg='lightblue')
self.info_label.place(x=50,y=190-20,width=180,height=30)
self.info1_label = Label(self.init_window_name,text="邮件发送状态:",bg='lightblue')
self.info1_label.place(x=50,y=325-20,width=180,height=30)
# 设置输入框应该与标签同一竖直--x相同
# self.input_1 = StringVar()
# self.attach_dir = Entry(self.init_window_name,textvariable=input_1)
# self.attach_dir.place(x=50,y=88,width=300,height=30)
# self.input_2 = StringVar()
# self.book_dir = Entry(self.init_window_name,textvariable=input_2)
# self.book_dir.place(x=50,y=158,width=300,height=30)
self.attach_dir = Label(self.init_window_name,text="",relief='groove',justify='left')
self.attach_dir.place(x=50,y=88-20,width=400,height=30)
self.book_dir = Label(self.init_window_name,text="",relief='groove',justify='left')
self.book_dir.place(x=50,y=158-20,width=400,height=30)
# 设置按钮--应该与输入框同一水平--y相同
self.attach_button = Button(self.init_window_name,text="选择文件夹",bg='lightblue',width=15,command=self.selectAttachDir)
self.attach_button.place(x=460,y=88-20,width=80,height=30)
self.book_button = Button(self.init_window_name,text="选择通讯录",bg='lightblue',width=15,command=self.selectBookFile)
self.book_button.place(x=460,y=158-20,width=80,height=30)
# 设置邮件内容
self.info_text = ScrolledText(self.init_window_name)
self.info_text.place(x=50,y=220-20,width=500,height=100)
self.info_text.insert(INSERT,"")
self.info_text.insert(END,"")
#print("邮件内容:"+str(self.info_text.get(1.0,END)))
# print(type(self.info_text.get(END)))
# print(self.info_text.get(0.0,END))
# 获取邮件发送状态
self.info1_text = ScrolledText(self.init_window_name)
self.info1_text.place(x=50,y=360-25,width=500,height=100)
self.info1_text.insert(INSERT,"")
self.info1_text.insert(END,"")
# 设置确定/取消按钮
self.finish_button = Button(self.init_window_name,text="确定",bg='lightblue',width=15,command=self.start_send_mail) # command=self.test
self.finish_button.place(x=460,y=430+10,width=80,height=30) #
self.cancel_button = Button(self.init_window_name,text="取消",bg='lightblue',width=15,command=self.init_window_name.quit)
self.cancel_button.place(x=370,y=430+10,width=80,height=30) #
# 选择附件目录
def selectAttachDir(self):
self.attachDir = askdirectory()
# print(type(self.attachDir)) # <class 'str'>
# self.input_1.set(attachDir)
self.attach_dir.config(text=self.attachDir) # 将结果显示在label上
# 选择通讯录文件
def selectBookFile(self):
self.bookFile = askopenfilename()
# print(type(self.bookFile)) # <class 'str'>
# self.input_2.set(bookFile)
self.book_dir.config(text=self.bookFile)
# 测试如何获取 ScrolledText 中的文本内容
def test(self):
print(type(self.info_text.get(END))) # str格式
print(self.info_text.get(0.0,END)) # 获取ScrolledText中的文本内容-正文
# print(self.attach_dir.get()) # 'Label' object has no attribute 'get'
# print(self.book_dir.get())
print(self.attach_dir['text']) # 获取label中的文本内容-目录
print(self.book_dir['text']) # 获取label中的文本内容-通讯录
self.init_window_name.quit
# # 开始发送邮件--attach_path,bookFile,mail_content
def start_send_mail(self):
# attach_path = self.attach_dir['text']
# bookFile = self.book_dir['text']
# mail_content = self.info_text.get(0.0,END)
# BatchsMailSender.mailSend(attach_path,bookFile,mail_content)
BatchsEmailSender.mailSend(self.attach_dir['text'],self.book_dir['text'],self.info_text.get(0.0,END))
self.init_window_name.quit
def gui_start():
init_window = tkinter.Tk()
main_gui = MyGUI(init_window)
main_gui.set_init_window()
init_window.mainloop()
# gui_start()
# 判断是否过试用期
def if_expired():
end_time = '2022-11-26 10:00:00' # 设置截止时间
end_time = time.strptime(end_time,'%Y-%m-%d %H:%M:%S')
end_time = int(time.mktime(end_time))
cur_time = int(time.time()) # 获取当前时间
left_time = end_time - cur_time # 剩余时间
if left_time <= 0:
warning_window = tkinter.Tk()
warning_window.title("批量发送邮件【根据csv读取收件人姓名和邮件地址,然后发送对应名称的文件】 ")
warning_window.geometry('600x480+300+200') # 设置尺寸
warning_window.attributes('-alpha',1) # 属性
tkinter.messagebox.showwarning(title="温馨提示",message="试用期已过,如需续用,请联系作者邮箱")
warning_window.mainloop()
sys.exit()
else:
pass
if __name__ == '__main__':
# 判断是否到期
if_expired()
# 正常运行
gui_start()
```