phppythonemaildictionaryimapclient

Using IMAPClient in Python to fetch email - need data to be stored in a list


Happy New Year to all of you :)

I built a web form where new employees enter their data and have it send to an email address where I receive about 20 "sets" of data coming from PHP.

Vorname: $firstname  
Nachname: $lastname

and so on.

Now, when I fetch the email with python using IMAPClient I remove the MIME characters before and after the main message and am left with the following set of strings:

"\r\nNachname: Doe\r\nVorname: John\r\nStraße: Bahnhofstraße 3a\r\nPLZ: 67346\r\nOrt: Speyer\r\nGeschlecht: maennlich\r\nGeburtsdatum: 10.07.1983\r\nGeburtsname: \r\nGeburtsort: Speyer\r\nFamilienstand: ledig\r\nNationalität: deutsch\r\nKonfession: katholisch\r\nTelefon_1: 017666666666\r\nTelefon_2: \r\nHandy: \r\nE-Mail: mail@mail.com\r\nFax: \r\nQualifikation: hwfach\r\nAbschluss: fachhauswirtsch\r\nAufmerksam_durch: pdienstleist, zeitung\r\n"

I tried to .replace("\r","") and \n but key and value seem to be off.

Wondering how you guys would solve this problem?

I have a working script with a in-code dictionary - so the only thing missing now is a way to excerpt a dictionary from the email.

Hopefully someone can help me.

Cheers


Solution

  • Well, if your goal is to convert this string to a dictionary, you can do something like this:

    First split it by \r\n (where x is the string)

    k_vs = x.split("\r\n")
    

    Now, you can use a dict comprehension to create the dictionary

    _dct = {i.split(":")[0].strip():i.split(":")[1].strip() for i in k_vs if i}
    

    If you would prefer more verbose, a for loop would do the same thing:

    _dct = {}
    for i in k_vs:
        if i:
            key, value = i.split(":")
            _dct.update({key: value})
    

    DEMO:

    >>> x = "\r\nNachname: Doe\r\nVorname: John\r\nStraße: Bahnhofstraße 3a\r\nPLZ: 67346\r\nOrt: Speyer\r\nGeschlecht: maennlich\r\nGeburtsdatum: 10.07.1983\r\nGeburtsname: \r\nGeburtsort: Speyer\r\nFamilienstand: ledig\r\nNationalität: deutsch\r\nKonfession: katholisch\r\nTelefon_1: 017666666666\r\nTelefon_2: \r\nHandy: \r\nE-Mail: mail@mail.com\r\nFax: \r\nQualifikation: hwfach\r\nAbschluss: fachhauswirtsch\r\nAufmerksam_durch: pdienstleist, zeitung\r\n"
    >>> 
    >>> y = x.split("\r\n")
    >>> z = {i.split(":")[0].strip():i.split(":")[1].strip() for i in y if i}
    >>> z
    {'Geburtsdatum': '10.07.1983', 'Familienstand': 'ledig', 'Konfession': 'katholisch', 'Aufmerksam_durch': 'pdienstleist, zeitung', 'Ort': 'Speyer', 'Telefon_2': '', 'Vorname': 'John', 'PLZ': '67346', 'Geburtsname': '', 'Nationalit\xc3\xa4t': 'deutsch', 'E-Mail': 'mail@mail.com', 'Nachname': 'Doe', 'Telefon_1': '017666666666', 'Qualifikation': 'hwfach', 'Geburtsort': 'Speyer', 'Geschlecht': 'maennlich', 'Abschluss': 'fachhauswirtsch', 'Handy': '', 'Stra\xc3\x9fe': 'Bahnhofstra\xc3\x9fe 3a', 'Fax': ''}
    >>>