#!/usr/bin/env python # -*- coding: utf8 -*- # Copyright 2007 hisitech, SLU or its licensors, as # applicable. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import quopri # quoted printable emails import getpass, poplib # simple pop3 handling def lee_SMS(msg): """Lee un mensaje SMS a partir de un mensaje de correo electrónico. FIXME: usar quopri sólo si el mensaje es utf-8 con el encoding. >>> msg=['Message-ID: <176713.1184932558657.JavaMail.open@movilforum.com>', 'Date: Fri, 20 Jul 2007 13:55:58 +0200 (MEST)', 'From: open@movilforum.com', 'To: test@mail.com', 'Subject: OPEN SMS ', 'Mime-Version: 1.0', 'Content-Type: text/plain; charset=UTF-8', 'Content-Transfer-Encoding: quoted-printable', 'X-Mailer: msgsend', 'Return-Path: open@movilforum.com', 'X-OriginalArrivalTime: 20 Jul 2007 11:55:19.0656 (UTC) FILETIME=[D869C680:01C7CAC4]', '', 'Movil:34609609609', 'Texto:Espa=C3=B1a accion y otros indices=00', ''] >>> lee_SMS(msg) ('34609609609', u'Espa\\xf1a accion y otros indices\\x00') >>> msg=['From: open@movilforum.com ', 'Date: Jul 20, 2007 1:13 PM', 'Subject: OPEN SMS', 'To: test@mail.com', '', 'Movil:34620620620', 'Texto:Buenos dias Santi :)', '' ] >>> lee_SMS(msg) ('34620620620', u'Buenos dias Santi :)') """ for i in range(len(msg)): # Leemos Content-Type y encoding "al paso" if msg[i].startswith('Content-Type:'): try: ctype, encoding = map(str.strip, msg[i].split(':')[1].split(';')) encoding = encoding.split('=')[1].strip() except: encoding = 'ascii' # Encuentro el final de cabeceras (primera línea en blanco) if not msg[i]: break #cabeceras #heads=msg[:i] #cuerpo body=msg[i+1:] # primer match numero = body[0].split(':',1) if len(numero)>1: numero = numero[1] mensaje = body[1].split(':',1) if len(mensaje)>1: mensaje = unicode(quopri.decodestring(mensaje[1]),'utf8') return numero, mensaje else: return None # no es un SMS def _test(verbose): import doctest doctest.testmod(verbose=verbose) if __name__=='__main__': _test(verbose=True) #M = poplib.POP3_SSL('pop.gmail.com') #M.user('myuser') #M.pass_(getpass.getpass()) #M.pass_('!mypasswd') #for mid, longitud in [i.split() for i in M.list()[1]]: #mid = int(mid) #longitud = int(longitud) #ret, msg, size = M.retr(mid) #print lee_SMS(msg) #for j in msg: # print j