批量发送邮件的小工具

  1. 老婆说他要发开发信,比较麻烦,都是模板发送,我说我可以搞个小程序,她说“你可以么”。。。试试吧
  2. 看看python核心编程,看了下gui编程,貌似就一些插件,然后关联上一些方法,看上去也不是很难。
  3. 主要程序
    import random
    from configparser import ConfigParser
    from functools import partial
    from tkinter import *
    from tkinter import ttk
    from tkinter import filedialog
    import time
    from sendemail import mail
    
    class MailGraph(object):
        def __init__(self):
            self.top = Tk(className="邮件发送器")
            self.pathtoEmailFile = StringVar(self.top)
            self.pathtoModelFile = StringVar(self.top)
            self.cm = StringVar(self.top) #显示当发送邮箱
            self.mt= StringVar(self.top)  #显示当前发送文本
            # 当前发送文本框
            self.LabelofcurrentMail = Label(self.top, text="当前发送邮箱:")
            self.LabelofcurrentMail.grid(row=1, column=0, padx=20, pady=1,sticky=E )
            self.currentMail = Entry(self.top, textvariable=self.cm, width=20)
            self.currentMail.grid(row=1, column=1, padx=20, pady=10, sticky=W)
            self.ButtonofChoseUserlist = Button(self.top, text="选择邮箱文件",
                                                command=partial(self.ChosePath, self.pathtoEmailFile))
            self.ButtonofChoseUserlist.grid(row=3, column=0, padx=20, pady=10,sticky=W)
            self.emailPath = Entry(self.top, textvariable=self.pathtoEmailFile, width=20)
            self.emailPath.grid(row=3, column=1, padx=20, pady=10,sticky=W)
            self.ButtonofChoseUserlist = Button(self.top, text="选择模板文件",
                                                command=partial(self.ChosePath, self.pathtoModelFile))
            self.ButtonofChoseUserlist.grid(row=3, column=2, padx=20, pady=10,sticky=W )
            self.modelPath = Entry(self.top, textvariable=self.pathtoModelFile)
            self.modelPath.grid(row=3, column=3, padx=5, pady=10)
    
    
            self.LabelofProcessRate = Label(self.top, text="发送进度" , width=10)
            self.LabelofProcessRate.grid(row=4, column=0, padx=20, pady=10,columnspan=2,sticky=W)
            self.ProcessRate = ttk.Progressbar(self.top, orient=HORIZONTAL, length=500, mode="determinate", )
            self.ProcessRate.grid(row=4, column=1, padx=20, pady=10,columnspan=2,sticky=W)
    
            self.ButtonofExecute = Button(self.top, text="开始发送", command=self.Execute)
            self.ButtonofExecute.grid(row=5, column=0, padx=20, pady=10, )
            self.errorinfo = StringVar(self.top)
            self.labeloferrorinfo = Label(self.top, textvariable=self.errorinfo, fg="red")
            self.labeloferrorinfo.grid(row=5, column=1, padx=5, pady=10, )
    
        def openfile(self):
            filename = filedialog.askopenfilename(title="选择txt文件", filetypes=[('txt', '*.txt')])
            return filename
    
        def readmailmodels(self, name):
            par = ConfigParser()
            par.read(name, encoding="utf-8")
            contents = []
            for sec in par.sections():
                contents.append(par.get(sec, 'content'))
            return contents
    
        def readdata(self, name):
            '''
            打开邮件列表文件,可以是每个一行,然后每行里可以用个逗号隔开
            :param name: 文件名
            :return: 列表
            '''
            emailList = []
            if name:
                with open(name, 'r', encoding='utf-8') as fr:
                    for line in fr:
                        emailList += line.replace(';', ',').split(',')
            return emailList
    
        def ChosePath(self, varname):
            '''选择用户列表'''
            fname = self.openfile()
            varname.set(fname)
    
        def Execute(self):
            '''执行过程'''
            # 检查两个模板是否选择
            emailfile = self.pathtoEmailFile.get()
            modelfile = self.pathtoModelFile.get()
            self.errorinfo.set("")
            if emailfile == "":
                self.errorinfo.set("请选择邮件列表")
            if modelfile == "":
                self.errorinfo.set("请选择模板列表")
            emails = self.readdata(emailfile)
            print(emails)
            modelfile = self.readmailmodels(modelfile)
            mailfuc = mail()
            totalemails = len(emails)
            curpro = 0
            for index in range(totalemails):
                content = random.choice(modelfile)
                mailfuc.send_mail([emails[index], ], cc=[emails[index], ], subject="你好", content=content)
                stepamount = 1.0 / totalemails * 100
                curpro += stepamount
                self.ProcessRate["value"] = curpro
                self.cm.set(emails[index])
                self.top.update()
                time.sleep(0.01)
    
    
    def main():
        m = MailGraph()
        mainloop()
    
    
    if __name__ == "__main__":
        main()
    

      

    #!/usr/bin/python
    #coding:utf-8
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.application import MIMEApplication
    
    class mail(object):
        def __init__(self,mail_host='smtp.163.com',mail_user='用户名',mail_pass='',mail_postfix='163.com',
                     nick_name='你的昵称'):
            self.mail_host = mail_host
    
            self.mail_user = mail_user
    
            self.mail_pass = mail_pass
    
            self.mail_postfix = mail_postfix
    
            self.nick_name = nick_name
    
        def send_mail(self,to_list,cc=None,subject=None,content=None,*filename):
             me = self.nick_name+"<"+self.mail_user+"@"+self.mail_postfix+">"
    
             msg = MIMEMultipart('mixed')
             msg['Subject'] = subject
             msg['From'] = me
             msg['to'] = ','.join(to_list)
             if cc:
                msg['CC'] = ','.join(cc)
             #文字部分
                to = to_list + cc
             else:
                 to = to_list
             part = MIMEText(content,_charset='utf-8')
             msg.attach(part)
             #附件部分
             for f in filename:
                 fp=open(f,'rb')
                 attach = MIMEApplication(fp.read())
                 fp.close()
                 attach.add_header('Content-Disposition','attachement',filename=f)
                 attach.set_charset('utf-8')
                 msg.attach(attach)
    
             try:
                  s = smtplib.SMTP()
                  s.connect(self.mail_host)
                  s.login(self.mail_user,self.mail_pass)
                  s.sendmail(me,to,msg.as_string())
                  s.close()
                  return True
             except Exception as e:
                  print(str(e))
                  return False
    

      

  4. tk的布局有绝对布局,相对布局,网格布局,百度了下,pack感觉没法用,堆一起,用了grid,最后图形界面当然还是挺丑的。。
  5.  

    邮箱文件 

    a@qq.com,b@qq.com,adfa@163.com
    aaf@163.com

    邮件模板文件

    [model1]
    content=你好,
                      这是我第一个邮件,请查收
                      第三行测试
    
    
    [model2]
    content=你好,这是我第二个邮件,请查收
    

      

posted @ 2021-12-18 20:36  打哈欠的星星  阅读(447)  评论(0编辑  收藏  举报