summaryrefslogtreecommitdiff
path: root/slime-0.11/slime_send.py
blob: 3e6c3b86ef677b1512d87ecbf759f98159ce87a5 (plain)
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
import smtplib, string, regex, regsub, pwd, os, socket, rfc822, time
import helpers, StringIO
from ui_config import config

draft_txt = """From: %s
Reply-to: %s
To: 
Cc: 
Subject: 

%s"""

reply_txt = """From: %s
Reply-to: %s
To: %s
Cc: %s
Subject: %s%s
In-Reply-To: %s
References: %s

%s:
%s

%s"""

_user_address = None

def deduce_user_address():
	global _user_address
	if config["from-address"]:
		return config["from-address"]
	if _user_address is None:
		userinfo = pwd.getpwuid(os.getuid())
		host = socket.gethostname()
		ip = socket.gethostbyname(host)
		fqdn = socket.gethostbyaddr(ip)[0]
		_user_address = "%s@%s" % (userinfo[0], fqdn)
		if userinfo[4]:
			x = regsub.sub(",*$", "", userinfo[4])
			_user_address = "%s <%s>" % (x, _user_address)
	return _user_address

def get_signature_text():
	try:
		pathname = os.path.expanduser(config["signature-file"])
		sig = "-- \n" + helpers.read_text_from_named_file(pathname)
	except IOError:
		sig = ""
	return sig

def make_new_message_text():
	return draft_txt % (deduce_user_address(), config["reply-to"], 
				get_signature_text())

def remove_duplicate_addrs(recipients, used_addrs):
	result = []
	for recipient in string.split(recipients, ","):
		name, addr = rfc822.parseaddr(recipient)
		if not addr in used_addrs:
			result.append(recipient)
			used_addrs.append(addr)
	return string.join(result, ","), used_addrs

def make_reply_message_text(msg):
	user_addr = deduce_user_address()
	reply_to = config["reply-to"]
	to_addrs = msg["to"]
	if to_addrs:
		to_addrs = msg["from"] + ", " + to_addrs
	else:
		to_addrs = msg["from"]
	cc_addrs = msg["cc"]
	
	user_addr_name, user_addr_addr = rfc822.parseaddr(user_addr)
	reply_to_name, reply_to_addr = rfc822.parseaddr(reply_to)

	if user_addr_addr and reply_to_addr:
		used_addrs = [user_addr_addr, reply_to_addr]
	elif user_addr_addr:
		used_addrs = [user_addr_addr]
	elif reply_to_addr:
		used_addrs = [reply_to_addr]
	else:
		used_addrs = []
	to_addrs, used_addrs = remove_duplicate_addrs(to_addrs, used_addrs)
	cc_addrs, used_addrs = remove_duplicate_addrs(cc_addrs, used_addrs)

	subject = msg["subject"]
	if string.lower(subject[:3]) == "re:":
		re = ""
	else:
		re = "Re: "

	msgid = msg["message-id"]
	refs = msg["references"] + " " + msgid
	while len(refs) > config["max-references-length"]:
		new_refs = regsub.sub("[^ ]* ", "", refs)
		if len(new_refs) == refs:
			break
		refs = new_refs

	quoted_author = msg["from"]
	quoted = msg.getbodytext()
	quoted = regsub.gsub("^", "> ", quoted)
	if quoted and quoted[-1] != "\n":
		quoted = quoted + "\n"
	
	return reply_txt % (user_addr, reply_to, to_addrs, 
				cc_addrs, re, subject, msgid, refs, 
				quoted_author, quoted, get_signature_text())

empty_trans = string.maketrans("", "")
sevenbit_chars = None

def deduce_charset(str):
	"""Deduce the character set used in a string."""
	global sevenbit_chars
	if not sevenbit_chars:
		list = []
		for code in range(128):
			list.append(chr(code))
		sevenbit_chars = string.join(list, "")
	if string.translate(str, empty_trans, sevenbit_chars):
		return "ISO-8859-1"
	return "us-ascii"

empty_header = regex.compile("^[^:][^:]*:[ \t]*$")
date_header = regex.compile("^Date:", regex.casefold)

def prepare_for_send(msg):
	nonempty = []
	hit = 0
	for line in string.split(msg.getheadertext(), "\n"):
		if line and not line[0] in string.whitespace:
			if date_header.match(line) == -1:
				hit = (empty_header.match(line) == -1)
			else:
				hit = 0
		if line and hit:
			nonempty.append(line)
	nonempty.append("Date: %s" % helpers.rfc822_date())
	nonempty.append("")
	headers = string.join(nonempty, "\n")

	msg.change_text(StringIO.StringIO(headers + "\n" + msg.getbodytext(0)))

def send_msg(msg):
	name, sender = msg.getaddr("from")
	receivers = []
	for header in ["to", "cc"]:
		if msg[header]:
			for name, addr in msg.getaddrlist(header):
				receivers.append(addr)

	smtp = smtplib.SMTP(config["smtp-server"])
	smtp.helo()
	smtp.mail_from(sender)
	for receiver in receivers:
		smtp.rcpt_to(receiver)
	text = string.split(msg.getfulltext(), "\n")
	smtp.data(text)
	smtp.quit()

def main():
	print deduce_user_address()
	print rfc822_date()
	print deduce_charset("this is us-ascii")
	print deduce_charset("tämä on latin1:tä")

if __name__ == "__main__":
	main()