发送邮件,可带附件,可群发

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

# 这是发布本信息时的版本,请以github上的为主要参考
def send_email(login=None, mail=None, images=None, attachments=None, use_ssl=None):
    smtpserver = login.get("smtpserver")
    username = login.get("username")
    password = login.get("password")
    email_type = mail.get('email_type')
    From = mail.get('from')
    To = mail.get('to')
    Subject = mail.get('subject')
    content = mail.get('content')

    if not To:
        To = username
    if isinstance(To, list):
        To = ','.join(To)

    if not email_type or (email_type not in ("plain", "html")):
        email_type = "html"
    
    main_msg = MIMEMultipart()   
    main_msg['Subject'] = Subject
    main_msg['From'] = From
    main_msg['To'] = To
    text_msg = MIMEText(content, email_type, 'utf-8')
    main_msg.attach(text_msg)

    if images:
        for f in images:
            fp = open(f, 'rb')
            img_msg = MIMEImage(fp.read()) 
            fp.close()
            
            basename = os.path.basename(f)
            img_msg.add_header('content-disposition',
                               'image' + str(images.index(f)), filename=basename)
            main_msg.attach(img_msg)

    if attachments:
        for f in attachments:
            basename = os.path.basename(f)
            if "." in basename:   
                content_type = mimetypes.types_map["." + basename.split(".")[-1]]
            else:                 
                content_type = 'application/octet-stream'
            maintype, subtype = content_type.split('/', 1)

            fp = open(f, 'rb')
            file_msg = MIMEBase(maintype, subtype)
            file_msg.set_payload(fp.read())
            fp.close()

            encoders.encode_base64(file_msg)
            
            file_msg.add_header('Content-Disposition',
                                'attachment' + str(images.index(f)), filename=basename)
            main_msg.attach(file_msg)

    smtp = smtplib.SMTP(smtpserver)
    if use_ssl:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()

    smtp.login(username, password)
    smtp.sendmail(From, To, main_msg.as_string())
    smtp.quit()