#!/usr/bin/env python3

import os, sys, smtplib, time, imaplib, email, yagmail

mons={'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06', \
      'Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}

app_password='password'
user='your_name@gmail.com'
ORG_EMAIL   = "@gmail.com"
FROM_EMAIL  = "your_name" + ORG_EMAIL
FROM_PWD    = "password"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT   = 993

heads=['From','To','CC','Date','Subject']
mail=yagmail.SMTP(user,app_password)

if '-h' in sys.argv:
  print('tiny_mail - tiny email client')
  print('all options of with new gmail two-step, just reponds to sys.argv[-1]')
  print()
  print('default, respond to top email, or N email')
  print()
  print('options: -l = list emails')
  print('         -d = delete number N')
  print('         -w = compose new email')
  print('         -s = display N email')
  sys.exit()

out=open('mail.tmp','w')
outbound=sys.argv[-1]
if '@' not in outbound: outbound='jschombe@gmail.com'
out.write('To: '+outbound+'\n')
out.write('Subject: \n\n'+50*'-'+'\n\n\n')
out.close()
os.system('/usr/bin/vim -X -c "set textwidth=65" +7 mail.tmp')
lines=[tmp[:-1] for tmp in open('mail.tmp','r').readlines()]
xmsg='' ; addr=[] ; prt=0
for line in lines:
  if 'To' in line:
    for z in line.replace(',',' ').split():
      if '@' in z: addr.append(z.replace(',',''))
  if 'CC' in line:
    for z in line.replace(',',' ').split():
      if '@' in z: addr.append(z.replace(',',''))
  if 'Subject' in line:
    subject=line.replace('Subject: ','')
  if prt: xmsg=xmsg+line+'<br>'
  if 50*'-' in line: prt=1

bcc='your_name@gmail.com'
for x in addr: print('sending to',x)
mail.send(to=addr, bcc=bcc, subject=subject, contents=xmsg)

os.remove('mail.tmp')
sys.exit()

if '-d' in sys.argv:
  mail.store("{0}".format(int(sys.argv[-1])),'+X-GM-LABELS', '\\Trash')
  sys.exit()

if '-w' in sys.argv:
  out=open('mail.tmp','w')
  outbound=sys.argv[-1]
  if '@' not in outbound: outbound='jschombe@gmail.com'
  out.write('To: '+outbound+'\n')
  out.write('Subject: \n\n'+50*'-'+'\n\n\n')
  out.close()
  os.system('/usr/bin/vim -X -c "set textwidth=65" +7 mail.tmp')
  lines=[tmp[:-1] for tmp in open('mail.tmp','r').readlines()]
  xmsg='Content-Type: text/plain\nFrom: your_name@gmail.com\n'
  prt=0
  for line in lines:
    if 'To' in line:
      xmsg=xmsg+line+'\n'
    if 'CC' in line:
      xmsg=xmsg+line+'\n'
    if 'Subject' in line:
      xmsg=xmsg+line+'\n'
    if prt: xmsg=xmsg+line+'\n'
    if 50*'-' in line: prt=1

  addr=[]
  for line in lines:
    if 50*'-' in line: break
    for element in ['<','>','"']: line=line.replace(element,'')
    for z in line.replace(',',' ').split():
      print(z)
      if '@' in z:
        if z not in addr and 'your_name@gmail.com' not in z: addr.append(z)

  print('going to',addr)
  if input('Send? (y)/n: ') == 'n': sys.exit()
  bcc=['your_name@gmail.com']
  gmail_user = 'your_name@gmail.com'
  gmail_password = 'password'
  server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
  server.ehlo()
  server.login(gmail_user, gmail_password)
  server.sendmail('your_name@gmail.com',addr+bcc,xmsg)
  server.quit()
  sys.exit()

if '-l' in sys.argv:
  for i in range(latest_email_id,first_email_id-1, -1):
    typ, data = mail.fetch(i, '(RFC822)' )
    for response_part in data:
      if isinstance(response_part, tuple):
        msg = email.message_from_string(response_part[1])
        print('[%2.2i' % i+'] :',end=' ')
        print(msg['From'].replace('\r','').replace('"','').split('\n')[0][:40].ljust(40)+' :',end=' ')
        print(msg['Date'].split('\n')[0][:25]+' :',end=' ')
        print(msg['Subject'].split('\n')[0][:40])
  sys.exit()

try:
  iemail=int(sys.argv[-1])
except:
  iemail=latest_email_id

for i in range(latest_email_id,first_email_id-1, -1):
  typ, data = mail.fetch(i, '(RFC822)' )
  if i == iemail: break

for response_part in data:
  if isinstance(response_part, tuple):
    msg = email.message_from_string(response_part[1])

prt=0
if '-s' in sys.argv:
  print('From:',msg['From'].replace('\r','').replace('"','').split('\n')[0])
  print('Date:',msg['Date'].split('\n')[0][:25])
  print('Subject:',msg['Subject'].split('\n')[0])
  print()
  for z in data[0][1].split('\n'):
    if len(z) == 1: prt=1
    if prt: print(z)
  sys.exit()

out=open('mail.tmp','w')
for z in heads:
  try:
    if 'From' in z:
      out.write(('To:').ljust(10)+msg['From']+'\n')
    elif 'To' in z:
      out.write(('From:').ljust(10)+msg['To']+'\n')
    elif 'Subject' in z:
      if 'Re:' in msg[z]:
        out.write((z+':').ljust(10)+msg[z]+'\n')
      else:
        out.write((z+':').ljust(10)+'Re: '+msg[z]+'\n')
    else:
      out.write((z+':').ljust(10)+msg[z]+'\n')
  except:
    pass
out.write(50*'-'+'\n\n\n')
last=''
for z in data[0][1].split('\n'):
  if len(z) == 1: prt=1
  t=z.replace(chr(13),'')
  t=last+t.replace('=20','')
  try:
    if t[-1] == '=':
      last=t[:-1]
      continue
    else:
      last=''
  except:
    last=''

  if prt:
    out.write('> '+t+'\n')
out.close()

os.system('/usr/bin/vim -X -c "set textwidth=65" +7 mail.tmp')

lines=[tmp[:-1] for tmp in open('mail.tmp','r').readlines()]

xmsg='Content-Type: text/plain\n'
prt=0
for line in lines:
  if 'From' in line:
    xmsg=xmsg+line+'\n'
  if 'To' in line:
    xmsg=xmsg+line+'\n'
  if 'CC' in line:
    xmsg=xmsg+line+'\n'
  if 'Subject' in line:
    xmsg=xmsg+line+'\n'
  if prt: xmsg=xmsg+line+'\n'
  if 50*'-' in line: prt=1

# find email addresses
addr=[]
for line in lines:
  if 50*'-' in line: break
  for element in ['<','>','"']: line=line.replace(element,'')
  for z in line.split():
    if '@' in z:
      if z not in addr and 'your_name@gmail.com' not in z: addr.append(z)

print('going to',addr)
if input('Send? (y)/n: ') == 'n': sys.exit()
bcc=['your_name@gmail.com']
gmail_user = 'your_name@gmail.com'
gmail_password = 'password'
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail('your_name@gmail.com',addr+bcc,xmsg)
server.quit()
