From 53f823c97f91287d12f76b028098bf15d01bbd2c Mon Sep 17 00:00:00 2001 From: wxnacy <371032668@qq.com> Date: Thu, 11 Jul 2019 15:06:09 +0800 Subject: [PATCH] add email command --- VERSION | 2 +- bin/base/check | 3 +- bin/config/config.py | 53 ++++++++++++++++++++ bin/config/del | 6 +++ bin/config/get | 6 +++ bin/config/set | 6 +++ bin/email/rece | 113 +++++++++++++++++++++++++++++++++++++++++++ bin/email/send | 100 ++++++++++++++++++++++++++++++++++++++ bin/install/htop | 2 +- bin/install/redis | 25 ++++++++++ bin/kindle/push | 18 ++++--- bin/py/__init__.py | 0 bin/py/config.py | 67 +++++++++++++++++++++++++ bin/py/send_email.py | 87 +++++++++++++++++++++++++++++++++ bin/wshell | 11 ++--- 15 files changed, 483 insertions(+), 16 deletions(-) create mode 100755 bin/config/config.py create mode 100755 bin/config/del create mode 100755 bin/config/get create mode 100755 bin/config/set create mode 100755 bin/email/rece create mode 100755 bin/email/send create mode 100755 bin/install/redis create mode 100644 bin/py/__init__.py create mode 100755 bin/py/config.py create mode 100755 bin/py/send_email.py diff --git a/VERSION b/VERSION index 1cc9c18..dc1e644 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.5.8 +1.6.0 diff --git a/bin/base/check b/bin/base/check index 669cd24..b98975e 100755 --- a/bin/base/check +++ b/bin/base/check @@ -10,7 +10,8 @@ notinstall='' echo -e '\nInstall:' for i in gcc g++ make cmake git vim wget unzip expect openssl c++ ack \ - htop http dig pyenv python java mysql docker nginx openresty vagrant;do + htop http dig pyenv python java mysql docker nginx openresty vagrant \ + redis;do path=`command -v $i` if [ $path ];then echo -e "$i\tinstall on $path" diff --git a/bin/config/config.py b/bin/config/config.py new file mode 100755 index 0000000..c47b667 --- /dev/null +++ b/bin/config/config.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# Author: wxnacy(wxnacy@gmail.com) +# Description: 解析文件名 + +import configparser +import os + +CONFIG_PATH='{}/.config/wshell/config'.format(os.getenv("HOME")) + +conf = configparser.ConfigParser() +conf.read(CONFIG_PATH) + +def set_val(name, value): + sec = name.split('.')[0] + key = name.split('.')[1] + if sec not in conf: + conf[sec] = {} + conf[sec][key] = value + with open(CONFIG_PATH, 'w') as f: + conf.write(f) + f.close() + +def delete(name): + sec = name.split('.')[0] + key = name.split('.')[1] + if sec in conf and key in conf[sec]: + del conf[sec][key] + with open(CONFIG_PATH, 'w') as f: + conf.write(f) + f.close() + +def get_val(name): + sec = name.split('.')[0] + key = name.split('.')[1] + if sec in conf and key in conf[sec]: + print(conf[sec][key]) + + + +if __name__ == "__main__": + import sys + args = sys.argv[1:] + cmd = args[0] + + cmdswitch = { + "set": set_val, + "del": delete, + "get": get_val, + } + + cmdswitch[cmd](*args[1:]) + diff --git a/bin/config/del b/bin/config/del new file mode 100755 index 0000000..7e959f3 --- /dev/null +++ b/bin/config/del @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Author: wxnacy(wxnacy@gmail.com) +# Description: 删除配置 + +ws config config.py del $@ + diff --git a/bin/config/get b/bin/config/get new file mode 100755 index 0000000..e1a228b --- /dev/null +++ b/bin/config/get @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Author: wxnacy(wxnacy@gmail.com) +# Description: + +ws config config.py get $@ + diff --git a/bin/config/set b/bin/config/set new file mode 100755 index 0000000..58b490c --- /dev/null +++ b/bin/config/set @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Author: wxnacy(wxnacy@gmail.com) +# Description: + +ws config config.py set $@ + diff --git a/bin/email/rece b/bin/email/rece new file mode 100755 index 0000000..74ec5bf --- /dev/null +++ b/bin/email/rece @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# Author: wxnacy(wxnacy@gmail.com) +# Description: 发送邮件 + +import os +import sys +sys.path.append('{}/bin/py'.format(os.getenv("WS_HOME"))) +import imaplib +import traceback +import argparse +import io +from email.header import decode_header +from email import message_from_string +from email.utils import parseaddr +from urllib.parse import urlparse +from config import ws_conf +import reprlib + +class Email(): + def __init__(self, section): + self.sec = section + + def connect_imap(self): + imap_url = self.sec.folder + url_config = urlparse(imap_url) + conn = imaplib.IMAP4_SSL(host = url_config.hostname, + port=url_config.port) + print('已连接服务器') + conn.login(self.sec['from'], self.sec.imap_pass) + print('已登陆') + self.imap_conn = conn + + def list_email(self): + self.connect_imap() + self.imap_conn.select() + type, data = self.imap_conn.search(None, 'ALL') + print(type, data) + newlist=data[0].split() + newlist.reverse() + if not os.path.exists('/tmp/wshell/email'): + os.makedirs('/tmp/wshell/email') + print('sender\tsubject\tpath\tattachs') + for nl in newlist: + type, data = self.imap_conn.fetch(nl, '(RFC822)') + msg = message_from_string(data[0][1].decode('utf-8')) + result = parse_email_message(msg) + # print(result) + result['subject'] = reprlib.repr(result['subject']) + result['content'] = reprlib.repr(result['content']) + print('{sender[0]}\t{subject}\t{content_path}\t{attachs}'.format(**result)) + +def decode_str(msg, name): + '''解析字符串信息''' + val = msg.get(name) + value, charset = decode_header(val)[0] + if charset: + value = value.decode(charset) + return value + +def parse_email_message(msg): + '''解析邮件信息''' + subject = decode_str(msg, 'subject') + sender = parseaddr(decode_str(msg, 'from')) + to = parseaddr(msg.get("to")) + content = None + content_html = None + content_path = None + attachs = [] + for part in msg.walk(): + # print(part.get_content_type(), part.is_multipart(), part.get_filename()) + # if part.is_multipart(): + # # print(part.attach()) + # print(part.get_filename()) + # print(part.get_param("name")) + if not part.is_multipart(): + content_type = part.get_content_type() + if content_type == 'text/plain': + content = part.get_payload(decode=True).decode('utf-8') + elif content_type == 'text/html': + content_html = part.get_payload(decode=True).decode('utf-8') + content_path = '/tmp/wshell/email/{}.html'.format(str(hash(msg))) + with open(content_path, 'w') as f: + f.write(content_html) + f.close() + filename = part.get_filename() + if filename: + attachs.append(filename) + + result = dict(locals()) + result.pop('msg') + result.pop('content_type') + result.pop('part') + return result + +def init_args(): + '''初始化参数''' + parser = argparse.ArgumentParser(description='Reveice email') + parser.add_argument("emails", help='Receive emails', nargs='+') + parser.add_argument('-s', '--subject', required=True, help='Email subject') + parser.add_argument('-m', '--message', help='Email content message') + parser.add_argument('-a', '--attach', help='Email attachments', + action="append", default=[]) + + return parser.parse_args() + + +if __name__ == '__main__': + + # args = init_args() + # print(ws_conf.email) + e = Email(ws_conf.email) + e.list_email() diff --git a/bin/email/send b/bin/email/send new file mode 100755 index 0000000..ba5eec6 --- /dev/null +++ b/bin/email/send @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# Author: wxnacy(wxnacy@gmail.com) +# Description: 发送邮件 + +import os +import sys +sys.path.append('{}/bin/py'.format(os.getenv("WS_HOME"))) +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +from email.header import Header +from urllib.parse import urlparse +import smtplib +import traceback +import argparse +import io +from config import ws_conf + +class Email(): + def __init__(self, smtp_host, smtp_port, user, password, sender, + sender_name, **kwargs): + kw = locals() + kw.pop('self') + for k, v in kw.items(): + setattr(self, k, v) + + def connect(self): + '''建立连接''' + try: + smtpObj = smtplib.SMTP() + smtpObj.connect(self.smtp_host, self.smtp_port) + smtpObj.login(self.user, self.password) + + self.client = smtpObj + except smtplib.SMTPException as e: + traceback.print_exc(e) + + def send(self, receivers, subject, message=None, cc=[], attachs=[]): + ''' + 发送邮件 + ''' + self.connect() + msg = MIMEMultipart() + msg['From'] = Header(self.sender_name, 'utf-8') + msg['To'] = Header(','.join(receivers), 'utf-8') + if cc: + msg['Cc'] = Header(','.join(cc), 'utf-8') + msg['Subject'] = Header(subject, 'utf-8') + if message: + msg.attach(MIMEText(message)) + + for att in attachs: + att1 = MIMEText(open(att, 'rb').read(), 'base64', 'utf-8') + att1.add_header('Content-Disposition', 'attachment', + filename=os.path.basename(att)) + msg.attach(att1) + receivers.extend(cc) + try: + self.client.sendmail(self.sender, receivers, + msg.as_string()) + return True + except Exception as e: + traceback.format_exc(e) + return False + finally: + self.client.quit() + +def init_args(): + '''初始化参数''' + parser = argparse.ArgumentParser(description='Send email') + parser.add_argument("emails", help='Receive emails', nargs='+') + parser.add_argument('-s', '--subject', required=True, help='Email subject') + parser.add_argument('-m', '--message', help='Email content message') + parser.add_argument('-a', '--attach', help='Email attachments', + action="append", default=[]) + + return parser.parse_args() + + +if __name__ == '__main__': + + args = init_args() + # print(ws_conf.email) + email_conf = ws_conf.email + smtp_url = email_conf.smtp_url + url_config = urlparse(smtp_url) + smtp_host = url_config.hostname + smtp_port = url_config.port + user = email_conf['from'] + password = email_conf['smtp_pass'] + sender = email_conf['from'] + sender_name = email_conf.realname # 发送方名称 + print('Send email to {}'.format(args.emails)) + e = Email(**locals()) + # e.login_imap() + receivers = args.emails # 接收方邮箱 + subject = args.subject + msg = args.message + e.send(receivers, subject, msg, attachs=args.attach) + print('Success!') diff --git a/bin/install/htop b/bin/install/htop index f68c974..ead9046 100755 --- a/bin/install/htop +++ b/bin/install/htop @@ -1,6 +1,6 @@ #!/usr/bin/env bash -OS=`curl -L https://raw.githubusercontent.com/wxnacy/wshell/master/bin/base/os | bash` +OS=`ws os` OSS=(${OS}) SYS=${OSS[0]} VER=${OSS[1]} diff --git a/bin/install/redis b/bin/install/redis new file mode 100755 index 0000000..0f8c0e1 --- /dev/null +++ b/bin/install/redis @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +OS=`ws os` +OSS=(${OS}) +SYS=${OSS[0]} +VER=${OSS[1]} + +if [ ${SYS} == 'ubuntu' ] +then + + sudo apt update -y + sudo apt -y install redis + +elif [ ${SYS} == 'centos' ] +then + + sudo yum update -y + sudo yum -y install redis + +elif [ ${SYS} == 'Darwin' ] +then + + brew install redis + +fi diff --git a/bin/kindle/push b/bin/kindle/push index d4b2eee..66b58cc 100755 --- a/bin/kindle/push +++ b/bin/kindle/push @@ -1,14 +1,14 @@ #!/usr/bin/env bash # Author: wxnacy(wxnacy@gmail.com) # Description: 推送书籍到 kindle -# vim ${HOME}/.config/wshell/kindle/kindrc -# email=your_kindle@kindle.cn -# vim ${HOME}/.config/wshell/kindle/muttrc -# set smtp_url = "smtp://@:" -# set smtp_pass = "" -# set from = "" +# ws config set kindle.email +# ws config set email.smtp_url smtp://@: +# ws config set email.smtp_pass +# ws config set email.from . ${HOME}/.config/wshell/kindle/kindrc +email=$(ws config get kindle.email) +# echo $email path=$1 @@ -19,6 +19,10 @@ then fi echo "Begin push $path" -mutt $email -F ${HOME}/.config/wshell/kindle/muttrc -s $path -a $path < /dev/null +names=($(ws py parse_filename.py $path)) +name=${names[1]} +mutt $email -F ${HOME}/.config/wshell/kindle/muttrc -s $name -a $path < /dev/null +# echo $name +# ws email send $email -s $name -a $path echo 'Success!' diff --git a/bin/py/__init__.py b/bin/py/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bin/py/config.py b/bin/py/config.py new file mode 100755 index 0000000..79aafe5 --- /dev/null +++ b/bin/py/config.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# Author: wxnacy(wxnacy@gmail.com) +# Description: 解析文件名 + +import configparser +import os +import reprlib + +CONFIG_PATH='{}/.config/wshell/config'.format(os.getenv("HOME")) + +# conf = configparser.ConfigParser() +# conf.read(CONFIG_PATH) + +# def set_val(name, value): + # sec = name.split('.')[0] + # key = name.split('.')[1] + # if sec not in conf: + # conf[sec] = {} + # conf[sec][key] = value + # with open(CONFIG_PATH, 'w') as f: + # conf.write(f) + # f.close() + +# def delete(name): + # sec = name.split('.')[0] + # key = name.split('.')[1] + # if sec in conf and key in conf[sec]: + # del conf[sec][key] + # with open(CONFIG_PATH, 'w') as f: + # conf.write(f) + # f.close() + +# def get_val(name): + # sec = name.split('.')[0] + # key = name.split('.')[1] + # if sec in conf and key in conf[sec]: + # print(conf[sec][key]) + +class ConfigParser(): + def __init__(self, *filenames): + self._conf = configparser.ConfigParser() + self._conf.read(filenames) + + def read(self, *conf_path): + self._conf.read(conf_path) + + def __getattr__(self, name): + if name in self._conf.sections(): + return self.Section(self._conf[name]) + return self.Section() + + class Section(dict): + def __init__(self, sec={}): + super().__init__(sec) + # self.sec = sec + # self = sec + + def __getattr__(self, name): + return self.get(name) + + def __repr__(self): + return ''.format( + reprlib.repr(list(self.keys()))) + +ws_conf = ConfigParser(CONFIG_PATH) + diff --git a/bin/py/send_email.py b/bin/py/send_email.py new file mode 100755 index 0000000..88be0fb --- /dev/null +++ b/bin/py/send_email.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# Author: wxnacy(wxnacy@gmail.com) +# Description: 发送邮件 + +from email.mime.text import MIMEText +from email.header import Header +from urllib.parse import urlparse +import os +import sys +import smtplib +import traceback +import argparse + +class Email(): + def __init__(self, smtp_host, smtp_port, user, password, sender, + sender_name, **kwargs): + kw = locals() + kw.pop('self') + for k, v in kw.items(): + setattr(self, k, v) + + def connect(self): + '''建立连接''' + try: + smtpObj = smtplib.SMTP() + smtpObj.connect(self.smtp_host, self.smtp_port) + smtpObj.login(self.user, self.password) + + self.client = smtpObj + self.sender = self.sender + self.sender_name = self.sender_name + except smtplib.SMTPException as e: + traceback.print_exc(e) + + def send(self, receivers, subject, message, maintype='plain', cc=[]): + ''' + 发送邮件 + ''' + self.connect() + message = MIMEText(message, maintype, 'utf-8') + message['From'] = Header(self.sender_name, 'utf-8') + message['To'] = Header(','.join(receivers), 'utf-8') + if cc: + message['Cc'] = Header(','.join(cc), 'utf-8') + # message['Bcc'] = Header(','.join(receivers), 'utf-8') + message['Subject'] = Header(subject, 'utf-8') + receivers.extend(cc) + try: + self.client.sendmail(self.sender, receivers, + message.as_string()) + self.client.quit() + return True + except Exception as e: + traceback.format_exc(e) + self.client.quit() + return False + +def init_args(): + parser = argparse.ArgumentParser('Send email') + parser.add_argument("emails", type=str, help='Receive emails') + parser.add_argument('-s', '--subject', type=str, required=True, help='Email subject') + parser.add_argument('-t', '--text', type=str, help='Email content') + + return parser.parse_args() + +if __name__ == '__main__': + print(os.environ.get("smtp_url")) + url_config = urlparse(os.getenv("smtp_url")) + args = init_args() + smtp_host = url_config.hostname + print(smtp_host) + smtp_port = url_config.port + user = os.getenv("from") # 发送方邮箱 + password = os.getenv("smtp_pass") # 发送方密码 + sender = os.getenv("from") # 发送方邮箱 + sender_name = 'wxnacy' # 发送方名称 + email_args = dict(locals()) + email_args.pop('url_config') + email_args.pop('args') + + e = Email(**email_args) + receivers = [args.emails.split(',')] # 接收方邮箱 + subject = args.subject + msg = args.text + e.send(receivers, subject, msg) + diff --git a/bin/wshell b/bin/wshell index 97dd067..26eb354 100755 --- a/bin/wshell +++ b/bin/wshell @@ -37,23 +37,23 @@ help(){ } other(){ + args=($@) ws_home=$(ws home) SH=${ws_home}/bin/$1/$2 if [ -f $SH ];then - $SH $3 $4 $5 $6 + $SH ${args[@]:2} exit fi SH=${ws_home}/bin/$2/$1 if [ -f $SH ];then - $SH $3 $4 $5 $6 + $SH ${args[@]:2} exit fi - # SH=${0/%wshell/base\/$1} SH=${ws_home}/bin/base/$1 if [ -f $SH ];then - $SH $2 $3 $4 $5 $6 + $SH ${args[@]:1} exit fi @@ -61,7 +61,6 @@ other(){ } home() { - # echo ${WS_HOME} [ -z ${WS_HOME} ] && echo "$HOME/.wshell" || echo ${WS_HOME} } @@ -91,7 +90,7 @@ case "$1" in sha256) hash $1 $2;; sha512) hash $1 $2;; home) home;; - *) other $1 $2 $3 $4 $5 $6 $7;; + *) other $@;; esac