制作简易邮件发送带GUI界面
代码
import tkinter as tk
import smtplib
from email.mime.text import MIMEText
from functools import partial
from email.header import Header
from tkinter.colorchooser import askcolor
from email.mime.multipart import MIMEMultipart
import tkinter.filedialog
# 工具主窗口
def window():
"""创建主窗口"""
root = tk.Tk()
root.title("QQ邮箱发送工具")
root.resizable(width=0, height=0)
root.geometry("600x400+350+200")
"""收件人"""
receiver_mail = tk.StringVar()
receiver_persion = tk.Label(root, text="收件人:", font=("华文中宋", 12))
receiver_persion.place(x=20, y=10)
tk.Entry(root, width=28, textvariable=receiver_mail).place(x=90, y=10)
tk.Label(root, text="(Example: example@163.com)").place(x=320, y=10)
"""主题"""
theme_text = tk.StringVar()
theme = tk.Label(root, text="主题:", font=("华文中宋", 12))
theme.place(x=20, y=40)
global theme_input
theme_input = tk.Entry(root, width=28, textvariable=theme_text)
theme_input.place(x=90, y=40)
color = tk.Label(root, text="多彩主题")
color.place(x=320, y=40)
color.bind("<Button-1>", coloerchoice)
"""正文"""
tk.Label(root, text="正文:", font=("华文中宋", 12)).place(x=20, y=74)
text = tk.Text(root, width=62, height=15, insertbackground="green", font=("宋体", 11))
text.place(x=90, y=75)
"""附件"""
part = tk.Label(root, text="添加附件", font=("华文中宋", 11))
part.place(x=15, y=330)
part.bind("<Button-1>", send_part)
"""发送"""
sendmail = partial(send_mail, receiver_mail, theme_text, text)
send_button = tk.Button(root, text="发送", padx=50, pady=10, font=("黑体", 12), anchor='center', command=sendmail)
send_button.place(x=180, y=330)
"""退出"""
tk.Button(root, text="退出", font=("黑体", 12), anchor='w', padx=50, pady=10, command=quit).place(x=420, y=330)
root.mainloop()
# 调用颜色选择函数
def coloerchoice(event):
color = askcolor(color='black', title='颜色选择框')
theme_input.config(fg=color[1])
# 发送邮件函数
def send_mail(receiver, subject, messagetext):
"""发件人"""
sender = "1001110038@qq.com"
"""收件人"""
receiver = receiver.get()
"""设置发送的授权码,不用密码发送"""
send_code = 'zbejxplystfagokm'
"""定义发送邮件主题"""
subject = subject.get()
"""定义发送内容(第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码)"""
message = MIMEText(messagetext.get(1.0, 'end'), 'plain', 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
message['from'] = sender
message['to'] = receiver
"""发送邮件"""
smtp = smtplib.SMTP()
smtp.connect('smtp.qq.com')
smtp.login(sender, send_code)
smtp.sendmail(sender, receiver, message.as_string())
smtp.quit()
# 传入附件函数
def send_part(event):
global file_data
with tkinter.filedialog.askopenfile(title="选择上传文件", filetypes=[('文件', '.txt')]) as f:
file_data = f.read()
if __name__ == '__main__':
window()
效果展示
