Skip to content

Commit

Permalink
add email command
Browse files Browse the repository at this point in the history
  • Loading branch information
wxnacy committed Jul 11, 2019
1 parent a0dcb7a commit 53f823c
Show file tree
Hide file tree
Showing 15 changed files with 483 additions and 16 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.5.8
1.6.0
3 changes: 2 additions & 1 deletion bin/base/check
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
53 changes: 53 additions & 0 deletions bin/config/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy([email protected])
# 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:])

6 changes: 6 additions & 0 deletions bin/config/del
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Author: wxnacy([email protected])
# Description: 删除配置

ws config config.py del $@

6 changes: 6 additions & 0 deletions bin/config/get
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Author: wxnacy([email protected])
# Description:

ws config config.py get $@

6 changes: 6 additions & 0 deletions bin/config/set
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Author: wxnacy([email protected])
# Description:

ws config config.py set $@

113 changes: 113 additions & 0 deletions bin/email/rece
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy([email protected])
# 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()
100 changes: 100 additions & 0 deletions bin/email/send
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy([email protected])
# 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!')
2 changes: 1 addition & 1 deletion bin/install/htop
Original file line number Diff line number Diff line change
@@ -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]}
Expand Down
25 changes: 25 additions & 0 deletions bin/install/redis
Original file line number Diff line number Diff line change
@@ -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
18 changes: 11 additions & 7 deletions bin/kindle/push
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
#!/usr/bin/env bash
# Author: wxnacy([email protected])
# Description: 推送书籍到 kindle
# vim ${HOME}/.config/wshell/kindle/kindrc
# [email protected]
# vim ${HOME}/.config/wshell/kindle/muttrc
# set smtp_url = "smtp://<your_email>@<smtp_url>:<smtp_port>"
# set smtp_pass = "<email_password>"
# set from = "<your_email>"
# ws config set kindle.email <your_email>
# ws config set email.smtp_url smtp://<your_email>@<smtp_url>:<smtp_port>
# ws config set email.smtp_pass <email_password>
# ws config set email.from <your_email>

. ${HOME}/.config/wshell/kindle/kindrc
email=$(ws config get kindle.email)
# echo $email

path=$1

Expand All @@ -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!'

Empty file added bin/py/__init__.py
Empty file.
Loading

0 comments on commit 53f823c

Please sign in to comment.