aboutsummaryrefslogtreecommitdiffstats
path: root/mail2news.py
blob: adce6310bc95c93fb155afbbfece1638e2c3ae70 (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
"""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.

"""
from collections import OrderedDict
import email
#import logging
import os
import nntplib
from StringIO import StringIO
from re import findall
from socket import gethostbyaddr, gethostname
import sys


#logging.basicConfig(level=logging.DEBUG)
# This is the single source of Truth
# Yes, it is awkward to have it assymetrically here
# and not in news2mail as well.
VERSION = '0.9.10'
DESC = "The Python Gateway Script: news2mail mail2news gateway"


class mail2news(object):
    """news to mail gateway class"""

    def __init__(self):
        #    newsgroups = None  # Newsgroups: local.test,local.moderated...
        #    approved = None  # Approved: kame@aragorn.lorien.org
        if 'NNTPHOST' in os.environ:
            self.newsserver = os.environ['NNTPHOST']
        else:
            self.newsserver = 'localhost'

        self.port = 119
        self.user = None
        self.password = None

        self.hostname = gethostbyaddr(gethostname())[0]

        self.heads_dict, self.smtpheads, self.nntpheads = {}, {}, {}
        self.headers = []
        self.message = None

    def readfile(self, opt):

        self.message = email.message_from_file(sys.stdin)

        if (len(self.message) == 0) \
                and self.message.get_payload().startswith('/'):
            msg_file_name = self.message.get_payload().strip()
            del self.message
            with open(msg_file_name, 'r') as msg_file:
                self.message = email.message_from_file(msg_file)

        # introduce nntpheads
        if opt.newsgroup != '':
            self.message['Newsgroups'] = opt.newsgroup
        if opt.approver != '':
            self.message['Approved'] = opt.approver

        return 1

    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:

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

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

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

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

        except KeyError, message:
            print message

    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.message:
                    del self.message[head]

            if 'Message-Id' in self.message:
                msgid = self.message['Message-Id']
                del self.message['Message-Id']
                self.message['Message-Id'] = msgid
            else:
                msgid = '<pyg.%d@tuchailepuppapera.org>\n' % (os.getpid())
                self.message['Message-Id'] = msgid

        except KeyError, message:
            print message

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

        heads_dict = OrderedDict(self.message)
        for hdr in self.message.keys():
            del self.message[hdr]

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

        for k in head_set:
            if k in heads_dict:
                self.message[k] = heads_dict[k]

        for k in heads_dict:
            if not k.startswith('X-') and not k.startswith('X-Resent-') \
                    and k not in head_set:
                self.message[k] = heads_dict[k]

        for k in heads_dict:
            if k.startswith('X-'):
                self.message[k] = heads_dict[k]

        for k in heads_dict:
            if k.startswith('X-Resent-'):
                self.message[k] = heads_dict[k]

    def sendemail(self):
        "Talk to NNTP server and try to send email."
        # readermode must be True, otherwise we don't have POST command.
        server = nntplib.NNTP(self.newsserver, self.port, self.user,
                              self.password, readermode=True)

        server.post(StringIO(self.message.as_string()))

        server.quit()