from email.Parser import Parser as EmailParser

def getID(path):
    f = file(path)
    p = EmailParser()
    msg = p.parse(f, True)
    f.close()

    subj = msg.get('Subject')
    if subj is not None:
        if subj.startswith('Mail ping '):
            subj = subj[len('Mail ping '):]
        else:
            subj = None
    return subj

class TemplateMustNotHaveFieldError(Exception):
    """Probe email template must not have this field"""

    def __str__(self):
        return '%s: %r, %r' % (self.__doc__,
                               self[0],
                               self[1])

def setMsgField(msg, field, value):
    if msg[field] is not None:
        raise TemplateMustNotHaveFieldError, (field, msg[field])
        
    msg[field] = value

def setID(msg, ident):
    setMsgField(msg, 'Subject', 'Mail ping %s' % ident)
