aboutsummaryrefslogtreecommitdiffstats
path: root/mail2news.py
blob: 3011a4e9854cc42117994dc8771a0d9d3ff4a36d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""Mail to news gateway script. Copyright 2000 Cosimo Alfarano

Author: Cosimo Alfarano
Date: September 16 2000

mail2news.py - (C) 2000 by Cosimo Alfarano <Alfarano@Students.CS.UniBo.It>
You can use this software under the terms of the GPL. If we meet some day,
and you think this stuff is worth it, you can buy me a beer in return.

Thanks to md for this useful formula. Beer is beer.

Gets news email and sends it via SMTP.

class mail2news is  hopefully conform to rfc850.

"""

import sys
from os import getpid
from socket import gethostbyaddr, gethostname
import string
from re import findall
import nntplib
import pyginfo


class mail2news:
    """news to mail gateway class"""

    reader = None                # mode reader
#    newsgroups = None            # Newsgroups: local.test,local.moderated...
#    approved = None                # Approved: kame@aragorn.lorien.org
    newsserver = 'localhost'    # no comment :)
    port = 119
    user = None
    password = None

    hostname = gethostbyaddr(gethostname())[0]

    heads_dict, smtpheads, nntpheads = {}, {}, {}
    email, headers, body = [], [], []

    def readfile(self, opt):

        for line in sys.stdin.readlines():
            self.email.append(line)

        if(len(self.email) == 1 and self.email[0][0] == '/'):
            file = self.email[0][:-1]
            del self.email[0]
            for line in open(file, 'r').readlines():
                self.email.append(line)

        # introduce nntpheads
        if opt.newsgroup != '':
            # TODO put it directly to self.message when we have it
            self.nntpheads['Newsgroups:'] = opt.newsgroup + '\n'
        if opt.approver != '':
            self.nntpheads['Approved:'] = opt.approver + '\n'

        return 1

    def parseemail(self):
        """get news email from file or stdin and separate heads from body

        REMEBER: headers value has '\n' as last char.
            Use string[:-1] to ignore newline.
        """

        try:
            body = 0        # are we in body or in headers?

            for line in self.email:
                if not body and len(line) == 1:
                    body = 1    # starts email body section

                if not body:
                    try:
                        # if it is a multi-line header like Received:
                        if line[0] not in [' ', '\t']:
                            try:
                                head, value = string.split(line, ' ', 1)
                            except string.index_error:
                                value = ''
                            self.smtpheads[head] = value
                        else:
                            self.smtpheads[head] = '%s%s' % \
                                (self.smtpheads[head], line)
                    except (string.index_error), message:
                        print('line: %s' % line)
                        print('(probably missing couple "Header: value" in %s)'
                              % line)
                        sys.exit(1)

                elif len(line) > 0 and body:
                    self.body.append(line)

        except (string.index_error), message:
            print message
            sys.exit(1)

        return self.smtpheads, self.body

    def puthead(self, dict, list, key):
        """private, transform dict entries in list entries
        Appends key of dict to list, deleting it from dict.
        """

        if key in dict:
            list.append(key + ' ' + dict.get(key))
            del dict[key]
        else:
            return 0
        return 1

    def sortheads(self):
        """make list sorted by heads: From: To: Subject: first,
           others, X-*, X-Resent-* last"""

        # put at top
        set = ('Newsgroups:', 'From:', 'To:', 'X-To:', 'Cc:', 'Subject:',
               'Date:', 'Approved:', 'References:', 'Message-Id:')

        for k in set:
            self.puthead(self.heads_dict, self.headers, k)

        for k in self.heads_dict.keys():
            if k[:2] != 'X-' and k[:9] != 'X-Resent-' and k not in set:
                self.puthead(self.heads_dict, self.headers, k)

        for k in self.heads_dict.keys():
            if k[:2] == 'X-':
                self.puthead(self.heads_dict, self.headers, k)

        for k in self.heads_dict.keys():
            if k[:9] == 'X-Resent-':
                self.puthead(self.heads_dict, self.headers, k)

        return self.headers

    def mergeheads(self):
        """make a unique headers dictionary from NNTP and SMTP
        single headers dictionaries."""

        self.heads_dict = {}

        try:
            for header in self.smtpheads.keys():  # fill it w/ smtp old heads
                self.heads_dict[header] = self.smtpheads[header]

            # and replace them w/ nntp new heads
            for header in self.nntpheads.keys():
                self.heads_dict[header] = self.nntpheads[header]

        except KeyError, message:
            print message

        return self.heads_dict

    def addheads(self):
        """add new header like X-Gateway:
        """

        info = pyginfo.pygsinfo()

        try:
            self.heads_dict['X-Gateway:'] = info.PROGNAME + ' ' + \
                info.PROGDESC + ' - Mail to News\n'

# it is nntpheads stuff
#            if(self.newsgroups):
#                self.heads_dict['Newsgroups:'] = self.newsgroups

#            if(self.approved):
#                self.heads_dict['Approved:'] = self.approved

        except KeyError, message:
            print message

        return self.heads_dict

    def renameheads(self):
        """rename headers such as Resent-*: to X-Resent-*:

        headers renamed are useless or not rfc 977/850 copliant
        handles References/In-Reply-To headers
        """
        try:

### test
#   if(post):
#       if(post in self.heads_dict):
#           self.heads_dict['X-Original-' + post] = self.heads_dict[post]
#
#       self.heads_dict[post] = self.heads_dict[pre]
#       del(self.heads_dict[pre])
#
#   else:
#       if(pre[0:2] == 'X-' and pre in self.heads_dict):
#           self.heads_dict['X-Original-' + pre] = self.heads_dict[pre]
#       elif(not pre[0:2] == 'X-' and 'X-' + pre in self.heads_dict):
#           self.heads_dict['X-' + pre] = self.heads_dict[pre]
#       del(self.heads_dict[pre])
### end test

            for key in self.heads_dict.keys():
                if(key[:7] in ['Resent-']):
                    if ('X-' + key) in self.heads_dict:
                        self.heads_dict['X-Original-' + key] = \
                            self.heads_dict['X-' + key]
                    self.heads_dict['X-' + key] = self.heads_dict[key]
                    del self.heads_dict[key]

            # In rfc822 References: is considered, but many MUA doen't put it.
            if ('References:' not in self.heads_dict) and \
                    ('In-Reply-To:' in self.heads_dict):
                print self.heads_dict['In-Reply-To:']

                # some MUA uses msgid without '<' '>'
#                ref = findall('([^\s<>\']+@[^\s<>;:\']+)', \
                # but I prefer use RFC standards
                ref = findall('(<[^<>]+@[^<>]+>)',
                              self.heads_dict['In-Reply-To:'])

                # if found, keep first element that seems a Msg-ID.
                if(ref and len(ref)):
                    self.heads_dict['References:'] = '%s\n' % ref[0]

#            if('To:' in self.heads_dict):
#                self.heads_dict['X-To:'] = self.heads_dict['To:']
#                del self.heads_dict['To:']

        except KeyError, message:
            print message

        return self.heads_dict

    def removeheads(self, heads=None):
        """remove headers like Xref: Path: Lines:
        """

        try:
            # removing some others useless headers .... (From is not From:)

            rmheads = ['Received:', 'From', 'NNTP-Posting-Host:',
                       'X-Trace:', 'X-Compliants-To:', 'NNTP-Posting-Date:']
            if(heads):
                rmheads.append(heads)

            for head in rmheads:
                if head in self.heads_dict:
                    del self.heads_dict[head]

#            if 'From' in self.heads_dict: # neither 'From ' nor 'From:'
#                del self.heads_dict['From']

#            # neither 'From ' nor 'From:'
#            if 'NNTP-Posting-Host:' in self.heads_dict:
#                del self.heads_dict['']

#            if 'Lines:' in self.heads_dict:
#                del self.heads_dict['Lines:']

            # it is usually set by INN, if ng is moderated...
#            if 'Sender:' in self.heads_dict:
#                del self.heads_dict['Sender:']

            if 'Message-id:' in self.heads_dict:
                self.heads_dict['Message-Id:'] = self.heads_dict['Message-id:']
                del(self.heads_dict['Message-id:'])

            if 'Message-ID:' in self.heads_dict:
                self.heads_dict['Message-Id:'] = self.heads_dict['Message-ID:']
                del(self.heads_dict['Message-ID:'])

            # If message-id is not present, I generate it
            if 'Message-Id:' not in self.heads_dict:
                msgid = '<pyg.%d@tuchailepuppapera.org>\n' % (getpid())
                self.heads_dict['Message-Id:'] = msgid

        except KeyError, message:
            print message

        return self.heads_dict

    def sendemail(self):
        """Talk to NNTP server and try to send email."""
        try:
            n = nntplib.NNTP(self.newsserver, self.port, self.user,
                             self.password)

            if(self.reader):
                n.putline('mode reader')
                resp = n.getline()
                print resp

            resp = n.shortcmd('POST')

            # sett RFC977 2.4.2
            if resp[0] != '3':
                raise n.error_reply, str(resp)

            for line in self.headers:
                if not line:
                    break
                if line[-1] == '\n':
                    line = line[:-1]
                if line[:1] == '.':
                    line = '.' + line
                n.putline(line)

            for line in self.body:
                if not line:
                    break
                if line[-1] == '\n':
                    line = line[:-1]
                if line[:1] == '.':
                    line = '.' + line
                n.putline(line)

            n.putline('.')
            n.quit()
            return None
        except (nntplib.error_reply, nntplib.error_temp, nntplib.error_perm,
                nntplib.error_proto, nntplib.error_data), message:
            return 'NNTP: ' + str(message)