Python发邮件实例,并用Tkinter实现UI

一个偶然的机会我接触到Python语言,个人感觉Python是强大的工具语言。就下决心好好研究一下。废话少说,讲述下这个Demo的实现过程及源码。多谢指正!

第一步:最主要的工具包就是:smtplib。下面是基本的操作的核心代码:

<span style="font-size:14px;"># -*- coding: utf-8 -*-
# Import the email modules we'll need
import smtplib
from email.mime.text import MIMEText

if __name__=='__main__':
    #设置基本信息
    mail_server = 'smtp.sina.com'
    user_address = '发信人的邮箱地址'
    user_pass = '发信人的邮箱密码'
    #实例化SMTP_SSL
    _smtp = smtplib.SMTP_SSL()
    _smtp.connect(mail_server)
    #登录邮箱
    _smtp.login(user_address,user_pass)

    #下面是创建邮件信息,主要用到MIMEText.

    #设置收件人列表,类型可以是元祖和列表
    receivers = ['[email protected]','[email protected]']
    #设置邮件主题
    subject = 'Test Mail'
    #设置邮件内容
    content = 'Hello,guys\nHow are you?'
    #设置邮件实例
    msg = MIMEText(content,_subtyp='plain',_charset='gb2312')
    #对应设置
    msg['From'] = user_address
    msg['To'] = ";".join(receivers)
    msg['Subject'] = subject

    #发送邮件
    _smtp.sendmail(user_address,receivers,msg.as_string())

    print 'Successfully sent email'

    #测试结束</span></span>

第二步:用Tkinter实现UI。这个比较简单,直接给出代码:

<span style="font-size:14px;">#定义邮件管理窗口类
class MailGUI:
    def __init__(self):
        self.root = Tk()
        self.root.title('邮件发放器')
        workArea = Frame(self.root,width=500,height=500)
        workArea.pack()
        #tkMessageBox.askquestion(title='用户登录',message='打开登录窗口')
        #初始化窗口
        labelframe = LabelFrame(workArea,padx=5,pady=10)#text can empty
        labelframe.pack(fill='both')
        #发送按钮
        btn_frame = Frame(labelframe,width=400,height=50,bg='#CCCCCC')
        btn_frame.pack(fill='y')
        sand_btn=Button(btn_frame,text='发送',padx=3,pady=2,                        state='active',command=self.runSendMail)
        sand_btn.pack()
        #定义变量,保存客户输入结果
        self.v_subject=StringVar()
        self.v_receiver=StringVar()
        self.v_content=StringVar()

        #接收人
        receiver_frame = Frame(labelframe,width=400,height=50)
        receiver_frame.pack(fill='y')
        Label(receiver_frame,width=20,pady=5,justify='left',                        text='接收人').pack(side='left')
        Entry(receiver_frame,width=50,textvariable=self.v_receiver).pack(side='left')
        #主题
        subject_frame = Frame(labelframe,width=400,height=50)
        subject_frame.pack(fill='y')
        Label(subject_frame,width=20,pady=5,justify='left',                        text='主题  ').pack(side='left')
        Entry(subject_frame,width=50,textvariable=self.v_subject).pack(side='right')
        #邮件内容
        content_frame = Frame(labelframe,width=400,height=50)
        content_frame.pack(fill='y')
        Label(content_frame,width=20,pady=5,justify='left',                        text='内容  ').pack(side='left')
        self.T_content = Text(content_frame,width=38,height=4)
        self.T_content.pack(side='right')
        self.root.mainloop()</span>

需要说明的是:为了获取动态输入结果,用到StringVar()

     <span style="font-size:14px;">
        #定义变量,保存客户输入结果
        self.v_receiver=StringVar()

        #textvariable 绑定预定义的变量
        Entry(receiver_frame,width=50,textvariable=self.v_receiver).pack(side='left')
</span>

分步讲解结束,

运行界面如下:

  下面附上完整代码:

<span style="font-size:14px;"># -*- coding: utf-8 -*-
# Import the email modules we'll need
import smtplib
from email.mime.text import MIMEText
from Tkinter import *
import tkMessageBox
import sys

#定义邮件管理窗口类
class MailGUI:
    def __init__(self):
        self.root = Tk()
        self.root.title('邮件发放器')
        workArea = Frame(self.root,width=500,height=500)
        workArea.pack()
        #初始化窗口
        labelframe = LabelFrame(workArea,padx=5,pady=10)#text can empty
        labelframe.pack(fill='both')
        #发送按钮
        btn_frame = Frame(labelframe,width=400,height=50,bg='#CCCCCC')
        btn_frame.pack(fill='y')
        sand_btn=Button(btn_frame,text='发送',padx=3,pady=2,                        state='active',command=self.runSendMail)
        sand_btn.pack()
        #定义变量,保存客户输入结果
        self.v_subject=StringVar()
        self.v_receiver=StringVar()
        self.v_content=StringVar()

        #接收人
        receiver_frame = Frame(labelframe,width=400,height=50)
        receiver_frame.pack(fill='y')
        Label(receiver_frame,width=20,pady=5,justify='left',                        text='接收人').pack(side='left')
        Entry(receiver_frame,width=50,textvariable=self.v_receiver).pack(side='left')
        #主题
        subject_frame = Frame(labelframe,width=400,height=50)
        subject_frame.pack(fill='y')
        Label(subject_frame,width=20,pady=5,justify='left',                        text='主题  ').pack(side='left')
        Entry(subject_frame,width=50,textvariable=self.v_subject).pack(side='right')
        #邮件内容
        content_frame = Frame(labelframe,width=400,height=50)
        content_frame.pack(fill='y')
        Label(content_frame,width=20,pady=5,justify='left',                        text='内容  ').pack(side='left')
        self.T_content = Text(content_frame,width=38,height=4)
        self.T_content.pack(side='right')
        self.root.mainloop()

    def runSendMail(self):
        #tkMessageBox.askquestion(title='发送邮件',message='发送?')
        receiver=self.v_receiver.get()
        sub=self.v_subject.get()
        to_list=receiver.split(',')
        content=str(self.T_content.get('0.0',END)).strip()
        self.initSMTP('xxxxx','@sina.com','发信人密码')
        self.sendMail(sub,to_list,content)
        tkMessageBox.showinfo(title='系统提示',message='发送成功')
    def initSMTP(self,mail_user,mail_server_name,mail_password):
        self.mail_user = mail_user + mail_server_name
        self.mail_password = mail_password
        self.mail_server_name = mail_server_name
        self._smtp = smtplib.SMTP_SSL()
        self._smtp.connect(self.findMailServer())
        self._smtp.login(self.mail_user,self.mail_password)
    def sendMail(self,sub,to_list,mail_body):
        msg = MIMEText(mail_body,_subtype='plain',_charset='utf-8')
        msg["Accept-Language"]="zh-CN"
        msg["Accept-Charset"]="ISO-8859-1,utf-8"
        msg['Subject'] = sub
        msg['From'] = self.mail_user
        msg['To'] = ";".join(to_list)
        self._smtp.sendmail(self.mail_user,to_list,msg.as_string())
        self._smtp.quit()
    def findMailServer(self):
        server_name = str(self.mail_server_name).strip()
        server_dict = {'@sina.com':'smtp.sina.com',                       '@126.com':'smtp.126.com',                       '@163.com':'smtp.163.com',                       '@qq.com':'smtp.qq.com'}
        return server_dict[server_name]
try:
    reload(sys)
    sys.setdefaultencoding('utf-8')
    MailGUI()
except Exception,e:
    print str(e)</span>

谢谢阅读!

时间: 2024-08-03 02:34:44

Python发邮件实例,并用Tkinter实现UI的相关文章

python 发邮件乱码

来自:http://outofmemory.cn/code-snippet/1464/python-send-youjian-resolve-suoyou-luanma-question 使用python发邮件很简单,但是遇到乱码问题很烦恼. 乱码问题有几种:有发件人名称乱码,有标题乱码,也有正文乱码的问题. 要解决发件人名称乱码问题,必须使用Header,如下代码: from email.header import Header from = ("%s<[email protected]

48. Python 发邮件(1)

python发送邮件 1.通过python发邮件步骤: 前提:开通了第三方授权,可以使用smtp服务 1.创建smtp对象 2.连接smtp服务器,默认端口号都是25 3.登陆自己的邮箱账号 4.调用发送消息函数,参数:发件人.收件人.消息内容 5.关闭连接 2.邮件消息注册: 首先创建一个消息对象: msg = email.mime.multipart.MIMEMultipart()                     #通过这个类创建消息 msg['from'] = '[email pr

Python 发邮件例子

Python 发邮件例子 例子 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-04-23 16:12:33 # @Author : BenLam # @Link : https://www.cnblogs.com/BenLam/ import smtplib from email.mime.text import MIMEText from email.header import Header from email.mi

python发邮件出现乱码

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码. encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码. 另外对于一些包含特殊字符的编码,直接解码可能会报错,可以使用对于的参数来设置.如:s.decode("utf-8", "igno

python发邮件

import smtplib from email.mime.text import MIMEText from email.header import Header # 第三方 SMTP 服务 mail_host="smtp.qq.com" #设置服务器 mail_user="xxxxxx" #用户名 mail_pass="plcfthkdtpoxcabh" #口令QQ需要授权码 sender = '[email protected]' rec

49. Python 发邮件(2)

继续修改上面一节的发邮件代码 发送附件: (1)先找一个本地的文件 (2)打开文件,读出文件字符串 (3)通过MIMT ext()类来创建一个对象att,传入文件读出内容 (4)增加att的头部信息,并指定文件名字 (5)添加到msg消息中msg.attach(att) 样例: attfile = 'test.py' basename = os.path.basename(attfile) fp = open(attfile, 'rb') att = email.mime.text.MIMETe

python 发邮件脚本

相关模块介绍 发送邮件主要用到了smtplib和email两个模块,这里首先就两个模块进行一下简单的介绍:    1.smtplib模块 smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])   SMTP类构造函数,表示与SMTP服务器之间的连接,通过这个连接可以向smtp服务器发送指令,执行相关操作(如:登陆.发送邮件).所有参数都是可选的. host:smtp服务器主机名 port:smtp服务的端口,默认是25:如果在创建SMT

人生苦短之Python发邮件

#coding=utf-8 import smtplib from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText ''' 一些常用邮箱发件服务器及端口号 邮箱 发件服务器 非SSL协议端口 SSL协议端口 163 smtp.163.co

python 发邮件的脚本

不加参数,可以 输出帮助 ,及使用方法. 秘送的也是成功的.在收件与抄送 不会显示. # coding: utf-8 import sys import os import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from sm