2 require 'socket' # just for gethostname!
8 class SendmailCommandFailed < StandardError; end
10 class EditMessageMode < LineCursorMode
11 FORCE_HEADERS = %w(From To Cc Bcc Subject)
12 MULTI_HEADERS = %w(To Cc Bcc)
13 NON_EDITABLE_HEADERS = %w(Message-Id Date)
15 HookManager.register "signature", <<EOS
16 Generates a signature for a message.
18 header: an object that supports string-to-string hashtable-style access
19 to the raw headers for the message. E.g., header["From"],
21 from_email: the email part of the From: line, or nil if empty
23 A string (multi-line ok) containing the text of the signature, or nil to
24 use the default signature.
28 attr_accessor :body, :header
31 register_keymap do |k|
32 k.add :send_message, "Send message", 'y'
33 k.add :edit_message_or_field, "Edit selected field", 'e'
34 k.add :edit_to, "Edit To:", 't'
35 k.add :edit_cc, "Edit Cc:", 'c'
36 k.add :edit_subject, "Edit Subject", 's'
37 k.add :edit_message, "Edit message", :enter
38 k.add :save_as_draft, "Save as draft", 'P'
39 k.add :attach_file, "Attach a file", 'a'
40 k.add :delete_attachment, "Delete an attachment", 'd'
43 def initialize opts={}
44 @header = opts.delete(:header) || {}
47 @body = opts.delete(:body) || []
48 @body += sig_lines if $config[:edit_signature]
51 @message_id = "<#{Time.now.to_i}-sup-#{rand 10000}@#{Socket.gethostname}>"
53 @skip_top_rows = opts[:skip_top_rows] || 0
59 def lines; @text.length end
60 def [] i; @text[i] end
63 def handle_new_text header, body; end
65 def edit_message_or_field
66 if (curpos - @skip_top_rows) >= @header_lines.length
69 edit_field @header_lines[curpos - @skip_top_rows]
73 def edit_to; edit_field "To" end
74 def edit_cc; edit_field "Cc" end
75 def edit_subject; edit_field "Subject" end
78 @file = Tempfile.new "sup.#{self.class.name.gsub(/.*::/, '').camel_to_hyphy}"
79 @file.puts format_headers(@header - NON_EDITABLE_HEADERS).first
84 editor = $config[:editor] || ENV['EDITOR'] || "/usr/bin/vi"
86 mtime = File.mtime @file.path
87 BufferManager.shell_out "#{editor} #{@file.path}"
88 @edited = true if File.mtime(@file.path) > mtime
90 return @edited unless @edited
92 header, @body = parse_file @file.path
93 @header = header - NON_EDITABLE_HEADERS
94 handle_new_text @header, @body
101 !edited? || BufferManager.ask_yes_or_no("Discard message?")
105 fn = BufferManager.ask_for_filename :attachment, "File name (enter for browser): "
107 @attachments << Pathname.new(fn)
111 def delete_attachment
112 i = (curpos - @skip_top_rows) - @attachment_lines_offset
113 if i >= 0 && i < @attachments.size && BufferManager.ask_yes_or_no("Delete attachment #{@attachments[i]}?")
114 @attachments.delete_at i
123 buffer.mark_dirty if buffer
127 header, @header_lines = format_headers(@header - NON_EDITABLE_HEADERS) + [""]
128 @text = header + [""] + @body
129 @text += sig_lines unless $config[:edit_signature]
131 @attachment_lines_offset = 0
133 unless @attachments.empty?
135 @attachment_lines_offset = @text.length
136 @text += @attachments.map { |f| [[:attachment_color, "+ Attachment: #{f} (#{f.human_size})"]] }
142 header = MBox::read_header f
145 header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
146 header.each { |k, v| header[k] = parse_header k, v }
152 def parse_header k, v
153 if MULTI_HEADERS.include?(k)
154 v.split_on_commas.map do |name|
155 (p = ContactManager.contact_for(name)) && p.full_address || name
162 def format_headers header
164 headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
165 lines = make_lines "#{h}:", header[h]
166 lines.length.times { header_lines << h }
169 [headers, header_lines]
172 def make_lines header, things
177 [header + " " + things]
182 things.map_with_index do |name, i|
183 raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
187 (" " * (header.length + 1)) + name
188 end + (i == things.length - 1 ? "" : ",")
195 return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
196 return false if $config[:confirm_no_attachments] && mentions_attachments? && @attachments.size == 0 && !BufferManager.ask_yes_or_no("You haven't added any attachments. Really send?")#" stupid ruby-mode
197 return false if $config[:confirm_top_posting] && top_posting? && !BufferManager.ask_yes_or_no("You're top-posting. That makes you a bad person. Really send?") #" stupid ruby-mode
201 if @header["From"] =~ /<?(\S+@(\S+?))>?$/
204 AccountManager.default_account.email
207 acct = AccountManager.account_for(from_email) || AccountManager.default_account
208 BufferManager.flash "Sending..."
211 IO.popen(acct.sendmail, "w") { |p| write_full_message_to p, date, false }
212 raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
213 SentManager.write_sent_message(date, from_email) { |f| write_full_message_to f, date, true }
214 BufferManager.kill_buffer buffer
215 BufferManager.flash "Message sent!"
217 rescue SystemCallError, SendmailCommandFailed => e
218 Redwood::log "Problem sending mail: #{e.message}"
219 BufferManager.flash "Problem sending mail: #{e.message}"
225 DraftManager.write_draft { |f| write_message f, false }
226 BufferManager.kill_buffer buffer
227 BufferManager.flash "Saved for later editing."
230 def write_full_message_to f, date=Time.now, escape=false
231 m = RMail::Message.new
232 @header.each do |k, v|
233 next if v.nil? || v.empty?
243 m.header["Date"] = date.rfc2822
244 m.header["Message-Id"] = @message_id
245 m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
247 if @attachments.empty?
248 m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
250 m.body = sanitize_body m.body if escape
251 m.body += sig_lines.join("\n") unless $config[:edit_signature]
253 body_m = RMail::Message.new
254 body_m.body = @body.join
255 body_m.body = sanitize_body body_m.body if escape
256 body_m.body += sig_lines.join("\n") unless $config[:edit_signature]
257 body_m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
258 body_m.header["Content-Disposition"] = "inline"
261 @attachments.each { |fn| m.add_file_attachment fn.to_s }
266 ## TODO: remove this. redundant with write_full_message_to.
268 ## this is going to change soon: draft messages (currently written
269 ## with full=false) will be output as yaml.
270 def write_message f, full=true, date=Time.now
271 raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
272 f.puts format_headers(@header).first
274 Date: #{date.rfc2822}
275 Message-Id: #{@message_id}
280 Content-Type: text/plain; charset=us-ascii
281 Content-Disposition: inline
282 User-Agent: Redwood/#{Redwood::VERSION}
287 f.puts sanitize_body(@body.join)
288 f.puts sig_lines if full unless $config[:edit_signature]
296 text = BufferManager.ask :subject, "Subject: ", @header[field]
298 @header[field] = parse_header field, text
306 @header[field].join(", ")
311 contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
313 text = contacts.map { |s| s.longname }.join(", ")
314 @header[field] = parse_header field, text
323 def sanitize_body body
324 body.gsub(/^From /, ">From ")
327 def mentions_attachments?
328 @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
332 @body.join =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
336 p = PersonManager.person_for(@header["From"])
337 from_email = p && p.email
339 ## first run the hook
340 hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
341 return ["", "-- "] + hook_sig.split("\n") if hook_sig
343 ## no hook, do default signature generation based on config.yaml
344 return [] unless from_email
345 sigfn = (AccountManager.account_for(from_email) ||
346 AccountManager.default_account).signature
348 if sigfn && File.exists?(sigfn)
349 ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }