Browse Source

Add script

Phyks (Lucas Verney) 6 years ago
parent
commit
4d131cdb53
1 changed files with 156 additions and 0 deletions
  1. 156
    0
      emails_sms_free.py

+ 156
- 0
emails_sms_free.py View File

@@ -0,0 +1,156 @@
1
+#!/usr/bin/env python3
2
+
3
+import email
4
+import imaplib
5
+import json
6
+import os.path
7
+import requests
8
+import sys
9
+
10
+msg_ids = {}
11
+
12
+
13
+def get_subject(subject_header):
14
+    tmp = email.header.decode_header(subject_header)[0]
15
+    if tmp[1] is None:
16
+        return str(tmp[0])
17
+    else:
18
+        return tmp[0].decode(tmp[1])
19
+
20
+
21
+def send(url, msg, i=0):
22
+    full_url = url.replace('{$msg}', msg)
23
+    r = requests.get(full_url, verify=False)
24
+    if r.status_code == 200:
25
+        return True
26
+    elif r.status_code == 400:
27
+        print('Un paramètre obligatoire est manquant.')
28
+        return False
29
+    elif r.status_code == 402:
30
+        if i < 3:
31
+            print('Trop de SMS ont été envoyés en trop peu de temps, ' +
32
+                'le script réessayera dans 30 secondes.')
33
+            time.sleep(30)
34
+            send(url, msg, i+1)
35
+        else:
36
+            print('Impossible d\'envoyer le message dans la dernière minute ' +
37
+                  'et demie.')
38
+            return False
39
+    elif r.status_code == 403:
40
+        print('Identifiants incorrects ou service non activé.')
41
+        return False
42
+    elif r.status_code == 500:
43
+        print('Erreur côté serveur.')
44
+        return False
45
+
46
+
47
+def get_emails(imap_server, imap_user, imap_password, inbox):
48
+    global msg_ids
49
+
50
+    print('Connecting to '+imap_server+'… ', end='')
51
+    conn = imaplib.IMAP4_SSL(imap_server)
52
+    print('Connected')
53
+    to_send = []
54
+
55
+    try:
56
+        print('Logging as '+imap_user+'… ', end='')
57
+        retcode, capabilities = conn.login(imap_user, imap_password)
58
+    except:
59
+        print('Failed')
60
+        print(sys.exc_info()[1])
61
+        sys.exit(1)
62
+    print('Logged in')
63
+
64
+    try:
65
+        conn.select(inbox, readonly=True)
66
+        typ, tmp_msg_ids = conn.uid('search', None, 'ALL')
67
+        tmp_msg_ids = [i.decode('utf-8')
68
+                       for i in tmp_msg_ids[0].split()]
69
+        if imap_server in msg_ids:
70
+            diff_msg_ids = [i
71
+                            for i in tmp_msg_ids
72
+                            if i not in msg_ids[imap_server]]
73
+        else:
74
+            diff_msg_ids = tmp_msg_ids
75
+        msg_ids[imap_server] = tmp_msg_ids
76
+        if len(diff_msg_ids) == 0:
77
+            print("\tNo new emails")
78
+        else:
79
+            for i in diff_msg_ids:
80
+                typ, msg_data = conn.uid('fetch', i, '(RFC822)')
81
+                msg_parsed = email.message_from_bytes(msg_data[0][1])
82
+                for part in msg_parsed.walk():
83
+                    if part.get_content_charset() is None:
84
+                        # We cannot know the character set, so return decoded "something"
85
+                        text = part.get_payload(decode=True)
86
+                        continue
87
+
88
+                    charset = part.get_content_charset()
89
+
90
+                    if part.get_content_type() == 'text/plain':
91
+                        text = part.get_payload(decode=True).decode(str(charset))
92
+                        break
93
+                subject = get_subject(msg_parsed['Subject'])
94
+                print("\tNew email from "+msg_parsed['From'] +
95
+                      " : "+subject)
96
+                to_send.append({'server': imap_server,
97
+                                'id': i,
98
+                                'from': msg_parsed['From'],
99
+                                'subject': subject,
100
+                                'content': text})
101
+        return to_send
102
+    finally:
103
+        try:
104
+            conn.close()
105
+        except:
106
+            pass
107
+        conn.logout()
108
+
109
+
110
+if __name__ == '__main__':
111
+    # EDIT BELOW ACCORDING TO YOUR NEEDS
112
+    imap_servers = [{'server': 'SERVER',
113
+                     'login': 'LOGIN',
114
+                     'password': 'PASS',
115
+                     'inbox': 'INBOX'}
116
+                   ]
117
+    save_path = os.path.expanduser('~/.mails_free_api.json')
118
+    debug = False
119
+    url = "https://smsapi.free-mobile.fr/sendmsg?user={$user}&pass={$pass}&msg={$msg}"
120
+    user = 'IDENT'
121
+    password = 'PASS'
122
+    # YOU SHOULD NOT HAVE TO EDIT BELOW
123
+
124
+    url = url.replace('{$user}', user)
125
+    url = url.replace('{$pass}', password)
126
+
127
+    if os.path.isfile(save_path):
128
+        with open(save_path, 'r') as fh:
129
+            msg_ids = json.load(fh)
130
+
131
+    to_send = []
132
+    for imap_server in imap_servers:
133
+        to_send.extend(get_emails(imap_server['server'],
134
+                                  imap_server['login'],
135
+                                  imap_server['password'],
136
+                                  imap_server['inbox']))
137
+
138
+    if debug:
139
+        print("\nNew emails to send via SMS:")
140
+        print("\t", to_send)
141
+
142
+    i = 1
143
+    for data in to_send:
144
+        msg = ('New email from '+data['from']+'\n' +
145
+               data['subject']+'\n' +
146
+               str(data['content'][:700])+'...')
147
+        if send(url, msg):
148
+            print('Sent '+str(i)+'/'+str(len(to_send)))
149
+        else:
150
+            msg_ids[data['imap_server']].remove(data['id'])
151
+            print('Email '+str(i)+'/'+str(len(to_send))+' : Unable to send the text ' +
152
+                  'message, remove this email from parsed list.')
153
+        i += 1
154
+
155
+    with open(save_path, 'w') as fh:
156
+        json.dump(msg_ids, fh)