aboutsummaryrefslogtreecommitdiffstats
path: root/news2mail.py
blob: 71e0d179114967d6a9d2d98663ba858e23e0332a (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
"""News to mail gateway script. Copyright 2000 Cosimo Alfarano

Author: Cosimo Alfarano
Date: June 11 2000

news2mail.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 article and sends it via SMTP.

class news2mail is hopefully conform to rfc822.

normal (what pygs does) operations flow is:
1) reads from stdin NNTP article (readfile)
2) divide headers and body (parsearticle)
3) merges NNTP and SMTP heads into a unique heads
4) adds, renames and removes some heads
5) sorts remaining headers starting at top with Received: From: To: Subject:
    Date:, normal headers ending with X-* and Resent-* headers.

"""
from collections import OrderedDict
import email
import logging
import smtplib
from socket import gethostbyaddr, gethostname
import sys
import time

from mail2news import VERSION, DESC


# logging.basicConfig(level=logging.DEBUG)
class news2mail(object):
    """news to mail gateway class"""

    wlfile = None
    logfile = None

    sender = ''
    rcpt = ''
    envelope = ''

    smtpserver = 'localhost'

    hostname = gethostbyaddr(gethostname())[0]

    heads_dict, smtpheads, nntpheads = {}, {}, {}
    article, headers, body = [], [], []
    message = None

    debug = 1

    def readfile(self):
        self.message = email.message_from_file(sys.stdin)
        self.nntpheads = OrderedDict(self.message)

    @staticmethod
    def puthead(from_dict, out_list, key):
        """private, x-form dict entries in out_list entries"""
        if key in from_dict:
            out_list.append(key + ' ' + from_dict.get(key))
        else:
            return 0
        return 1

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

        # put at top
        header_set = ('Received', 'From', 'To', 'Subject', 'Date')

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

        for k in self.heads_dict.keys():
            if not k.startswith('X-') and not k.startswith('Resent-') \
                    and k not in header_set:
                self.puthead(self.heads_dict, self.headers, k)

        for k in self.heads_dict.keys():
            if k.startswith('X-'):
                self.puthead(self.heads_dict, self.headers, k)

        for k in self.heads_dict.keys():
            if k.startswith('Resent-'):
                self.puthead(self.heads_dict, self.headers, k)

        logging.debug('self.headers = %s', self.headers)
        return self.headers

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

        self.heads_dict = OrderedDict(self.nntpheads)
        self.heads_dict.update(self.smtpheads)

        return self.heads_dict

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

        self.heads_dict['X-Gateway'] = 'pyg {0} {1}'.format(VERSION, DESC)

        # to make Received: header
        t = time.ctime(time.time())

        if time.daylight:
            tzone = time.tzname[1]
        else:
            tzone = time.tzname[0]

        # An example from debian-italian:
        # Received: from murphy.debian.org (murphy.debian.org [216.234.231.6])
        #        by smv04.iname.net (8.9.3/8.9.1SMV2) with SMTP id JAA26407
        #        for <kame.primo@innocent.com> sent by
        #        <debian-italian-request@lists.debian.org

        tmp = 'from GATEWAY by ' + self.hostname + \
            ' with pyg' + \
            '\n\tfor <' + self.rcpt + '> ; ' + \
            t + ' (' + tzone + ')\n'

        self.heads_dict['Received'] = tmp

        return self.heads_dict

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

        headers renamed are useless or not rfc 822 copliant
        """
        try:
            if 'Newsgroups' in self.heads_dict:
                self.heads_dict['X-Newsgroups'] = \
                    self.heads_dict['Newsgroups']
                del self.heads_dict['Newsgroups']

            if 'NNTP-Posting-Host' in self.heads_dict:
                self.heads_dict['X-NNTP-Posting-Host'] = \
                    self.heads_dict['NNTP-Posting-Host']
                del self.heads_dict['NNTP-Posting-Host']
        except KeyError, message:
            print message

        return self.heads_dict

    def removeheads(self):
        """remove headers like Xref: Path: Lines:
        """

        try:
            # removing some others useless headers ....
            # that includes BOTH 'From ' and 'From'
            # 'Sender is usually set by INN, if ng is moderated...
            for key in ('Approved', 'From', 'Xref', 'Path', 'Lines', 'Sender'):
                if key in self.heads_dict:
                    del self.heads_dict[key]

            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:
                # It should put a real user@domain
                self.heads_dict['Message-Id'] = 'pyg@puppapera.org'

        except KeyError, message:
            print message

        return self.heads_dict

    def sendarticle(self):
        """Talk to SMTP server and try to send email."""
        try:
            raise NotImplementedError(
                'sendarticle does not use email.Message yet')

            msglist = []

            s = smtplib.SMTP(self.smtpserver)

            # put real locahost domain name.
            s.helo(self.hostname)
            if s.helo_resp is None and s.ehlo_resp is None:
                print 'No helo resp'
                sys.exit(1)

            resp = s.mail(self.envelope)
            if resp[0] != 250:
                print 'SMTP error during MAIL cmd: %s %s' % (resp[0], resp[1])
                print 'envelope %s gave problem?' % self.envelope
                sys.exit(1)
            resp = s.rcpt(self.rcpt)
            if resp[0] != 250:
                print 'SMTP error during MAIL cmd: %s %s' % (resp[0], resp[1])
                sys.exit(1)

            msglist.append(''.join(self.headers))

            msglist.append(''.join(self.body))
            msg = ''.join(msglist)

            s.data(msg)
            s.quit()

            return 1

        except (smtplib.SMTPException), messaggio:
            print messaggio
            sys.exit(1)