脚本篇-python smtplib自动发送邮件脚本(可定时)

脚本篇-python smtplib自动发送邮件脚本(可定时)


       工作中可能会重复性的发送一些邮件,或者为了增强员工的安全意识,模拟黑客发送钓鱼邮件。
       以下代码可以批量并且定时的发送邮件。
       建议使用qq邮箱或者foxmail,其他的邮箱会限制每天发送的量。QQ邮箱亲测大约每天可以发300封左右。
有可改进的地方,欢迎大佬指点。

#! python3

import smtplib
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formataddr
from email.header import Header
from email.mime.multipart import MIMEMultipart
import time
from email.utils import parseaddr
from email import encoders
import schedule
import threading
import os
import mimetypes
from itertools import islice


class EmailManager:
    def __init__(self, **kwargs):
        self.kwargs = kwargs
        self.smtp_server = 'smtp.qq.com'
        self.MAX_FILE_SIZE = 10 * 1024 * 1024

    def __get_cfg(self, key, throw=True):
        cfg = self.kwargs.get(key)
        if throw == True and (cfg is None or cfg == ''):
            raise Exception("The configuration can't be empty", 'utf-8')
        return cfg

    def __init_cfg(self):
        self.msg_from = self.__get_cfg('msg_from')
        self.password = self.__get_cfg('password')
        self.msg_to = ','.join(self.__get_cfg('msg_to'))
        self.msg_subject = self.__get_cfg('msg_subject')
        self.msg_content = self.__get_cfg('msg_content')
        self.msg_date = self.__get_cfg('msg_date')
        self.attach_file = self.__get_cfg('attach_file', throw=False)

    def login_server(self):

        server = smtplib.SMTP_SSL(self.smtp_server, 465)
        server.set_debuglevel(1)
        server.login(self.msg_from, self.password)
        return server

    def get_main_msg(self):
        msg = MIMEMultipart()
        msg.attach(MIMEText(self.msg_content, 'plain', 'utf-8'))

        msg['From'] = self._format_addr('收件人昵称' % self.msg_from)
        msg['To'] = self._format_addr('all')
        msg['Subject'] = Header(self.msg_subject, 'utf-8')
        msg['Date'] = self.msg_date
        attach_file = self.get_attach_file()
        if attach_file is not None:
            msg.attach(attach_file)
        return msg

    def get_attach_file(self):
        if self.attach_file is not None and self.attach_file != '':
            try:
                if os.path.getsize(self.attach_file) > self.MAX_FILE_SIZE:
                    raise Exception('The attachment is too large and the upload failed!!')
                with open(self.attach_file, 'rb') as file:
                    ctype, encoding = mimetypes.guess_type(self.attach_file)
                    if ctype is None or encoding is not None:
                        ctype = 'application/octet-stream'
                    maintype, subtype = ctype.split('/', 1)
                    mime = MIMEBase(maintype, subtype)
                    mime.set_payload(file.read())
                    mime.add_header('Content-Disposition', 'attachment',
                                    filename=os.path.basename(self.attach_file))
                    mime.add_header('Content-ID', '<0>')
                    mime.add_header('X-Attachment-Id', '0')
                    encoders.encode_base64(mime)
                    return mime
            except Exception as e:
                print('%s......' % e)
                return None
        else:
            return None

    def _format_addr(self, s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    def send(self):

        try:
            self.__init_cfg()
            server = self.login_server()
            msg = self.get_main_msg()
            server.sendmail(self.msg_from, self.__get_cfg('msg_to'), msg.as_string())
            server.quit()
            print("Send succeed!!")
            print(mail_addr)
        except smtplib.SMTPException:
            print("Error:Can't send this email!!")
            print(mail_addr)
            
    def run_threaded(manager):
        threading.Thread(target=manager.send()).start()

    def send_mail_by_schedule(manager):
        schedule.every(1).minutes.do(run_threaded, manager)  # 每5分钟执行一次

        while True:
            schedule.run_pending()
            time.sleep(1)
if __name__ == "__main__":
    with open("mail.txt", 'r') as f:
        mail_len = len(f.readlines())

        # print(mail_addr)
    i = 0
    j = 1

    while i < mail_len:
        mail_addr = []
        f = open("mail.txt")
        for a in islice(f, i, j):
            mail_addr.append(a.rstrip())

        mail_cfgs = {'msg_from': '真实邮箱', #如果不写真实邮箱,客户端会显示出是代发
                     'password': '授权码',
                     'msg_to': mail_addr,
                     'msg_subject': '标题',
                     'msg_content': """
                   您好:
                             此处填写正文内容。                 
                                    """,
                     'attach_file': '附件地址',
                     'msg_date': time.ctime()
                     }

        manager = EmailManager(**mail_cfgs)
        manager.send()

        # send_mail_by_schedule(manager) 定时发送
        i += 1
        j += 1
        time.sleep(10)#为了防止被ban掉ip

关注公众号,一起分享实用安全技术,关注安全最新事件,记录工作常见问题,吐槽生活真心操蛋。
在这里插入图片描述

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值