Skip to content

Instantly share code, notes, and snippets.

@widoyo
Created February 11, 2013 15:06
Show Gist options
  • Save widoyo/4754963 to your computer and use it in GitHub Desktop.
Save widoyo/4754963 to your computer and use it in GitHub Desktop.
Pembaca email (IMAP)
import re
import imaplib
import email
import datetime
import json
EMAIL_FROM = 'sparelog_hwi'
EMAIL_HOST = ''
EMAIL_USER = ''
EMAIL_PASS = ''
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import send_mail
from hsm.models import Pool
from hsm.models import HwiRequest
class Command(BaseCommand):
args = ''
help = 'Membaca email dari Huawei untuk simpan dan email ke Pool YBS'
pola = "APP NO\.\r\n\r\nPART NO\.\r\n\r\nRMA NO\.\r\n\r\nTT NO\. / SITE NAME\r\n\r\nORIGIN\r\n\r\nDESTINATION\r\n\r\nREMARKS\r\n\r\n(?P<app_no>.*)\r\n\r\n(?P<pn>.*)\r\n\r\n(?P<rma>.*)\r\n\r\n(?P<tt>.*)\r\n\r\n(?P<origin>.*)\r\n\r\n(?P<dest>.*)\r\n\r\n(?P<remarks>.*)\r\n"
regex = re.compile(pola)
def handle(self, *args, **options):
self.update_pool_good_part()
def handle_mail(self, *args, **options):
'''
Membaca email dari EMAIL_FROM yang belum terbaca
'''
mail = imaplib.IMAP4(EMAIL_HOST)
mail.login(EMAIL_USER, EMAIL_PASS)
mail.select('inbox')
result, data = mail.search(
None,
'(FROM %s)' % EMAIL_FROM,
'(UNSEEN)'
)
if not data:
raise CommandError("Tidak ada email baru")
ids = data[0].split()
for mid in ids:
result, data = mail.fetch(mid, '(RFC822)')
msg = data[0][1]
d = self.parse_msg(msg)
if d:
msg = email.message_from_string(msg)
# Simpan ke table hwi_request
date_str = msg.get('date')
if date_str:
date_tpl = email.utils.parsedate_tz(date_str)
if date_tpl:
edate = datetime.datetime.fromtimestamp(
email.utils.mktime_tz(date_tpl)
)
if not edate:
edate = datetime.datetime.now()
else:
edate = datetime.datetime.now()
hr = HwiRequest(edate=edate,
order_num=d.get('app_no', '?').strip(),
pn=d.get('pn', '?').strip(),
rma=d.get('rma', '?').strip(),
tt_site=d.get('tt', '?').strip(),
pool_code=d.get('origin', '?').strip(),
destination=d.get('dest', '?').strip(),
remarks=d.get('remarks', '-').strip())
hr.save()
# Kirim email ke Pool
try:
pool = Pool.objects.get(code=d.get('origin'))
email_to = 'sphw_%[email protected]' % (pool.name)
subject = 'Permintaan RMA %s' % (d.get('rma'))
message = "Silakan tengok RMA lengkap di http://hwi.sparelog.com/rma/%s/\n\nJANGAN DIBALAS EMAIL INI." % (d.get('rma'))
send_mail(subject, message, '[email protected]',
[email_to])
except Pool.DoesNotExist:
pass
# Menandai email telah dibaca
mail.store(mid, '+FLAGS', '\\Seen')
mail.logout
def parse_msg(self, msg):
'''
Membaca isi email dan meneruskan ke email Pool
msg: string raw email
'''
msg = email.message_from_string(msg)
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get_content_type() == 'text/plain':
mail_content = part.get_payload(decode=True)
r = self.regex.search(mail_content)
return r and r.groupdict() or False
def update_pool_good_part(self):
'''
Mengupdate file ringkasan banyak sparepart per pool
output: file 'templates/pool_good_part.json'
'''
top = 10
pool_data = [(p.name.title(), p.num_good_part())
for p in Pool.objects.all() if p.num_good_part() > 0]
pool_data = sorted(pool_data, key=lambda good: good[1])[::-1]
lainnya = 0
new_data = pool_data[0:top]
if len(pool_data) > top:
lainnya = sum([p[1] for p in pool_data[top:]])
new_data.append(('Lainnya', lainnya))
new_data.insert(0, ('Pool', 'Module'))
of = open('templates/data/good_part.json', 'w')
of.write(json.dumps(new_data))
of.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment