func_send_all_dir.py 3.33 KB
# -*- coding: utf-8 -*-
"""
Created on Mon Apr  9 07:41:59 2018

Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  

Attachments size should be checked BEFORE call this function, because 
different SMTP servers apply different size limits. 

@author: hanye
"""

import os, sys, datetime
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

#from argparse import ArgumentParser

from email.message import EmailMessage
from email.policy import SMTP


def send_all_dir(subject, message, smtp_host,
                 sender, recipients, 
                 directory='.', attachments=[], output=None,
                 f_log=sys.stdout):
    
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['To'] = ', '.join(recipients)
    msg['From'] = sender
    msg.preamble = 'Email message preamble.\n'
    
    email_msg_body=message
    msg.set_content(email_msg_body)

    if len(attachments)==0:
        attachments=os.listdir(directory)
    for filename in attachments:
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    send_email_success=False
    if output!=None:
        with open(output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        try:
            send_s=datetime.datetime.now()
            with smtplib.SMTP(host=smtp_host) as s:
                s.send_message(msg)
            send_e=datetime.datetime.now()
            send_t_delta=send_e-send_s
            print('Successfully sent email to %s from %s, takes %s,' % (','.join(recipients), sender, send_t_delta),
                  datetime.datetime.now(), file=f_log) 
            
            send_email_success=True
            return send_email_success
            
        except:
            print('Failed to send email with attachments.', datetime.datetime.now(), file=f_log)
            return send_email_success

if __name__ == '__main__':
    pth=r'D:\CSM\Docs\Projects\短视频\code\maintainance\send_recev_email\test'
    sender='hanye@csm.com.cn'
    csm_mail_service='mail.csm.com.cn'
    recr='hanye@csm.com.cn'
    subject='这是测试数据邮件附件3'
    message_body="""
您好,

这是测试邮件附件

祝好,
韩烨
"""
    attachments=['email_test.py', 'videonumber_alert_daily_test.py']
    send_all_dir(subject=subject, message=message_body, 
                 directory=pth, attachments=attachments,
                 sender=sender, smtp_host=csm_mail_service, recipients=[recr])