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 unless @attachments.empty?
133 @attachment_lines_offset = @text.length
134 @text += @attachments.map { |f| [[:attachment_color, "+ Attachment: #{f} (#{f.human_size})"]] }
140 header = MBox::read_header f
143 header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
144 header.each { |k, v| header[k] = parse_header k, v }
150 def parse_header k, v
151 if MULTI_HEADERS.include?(k)
152 v.split_on_commas.map do |name|
153 (p = ContactManager.contact_for(name)) && p.full_address || name
160 def format_headers header
162 headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
163 lines = make_lines "#{h}:", header[h]
164 lines.length.times { header_lines << h }
167 [headers, header_lines]
170 def make_lines header, things
175 [header + " " + things]
180 things.map_with_index do |name, i|
181 raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
185 (" " * (header.length + 1)) + name
186 end + (i == things.length - 1 ? "" : ",")
193 return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
194 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
195 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
199 if @header["From"] =~ /<?(\S+@(\S+?))>?$/
202 AccountManager.default_account.email
205 acct = AccountManager.account_for(from_email) || AccountManager.default_account
206 BufferManager.flash "Sending..."
209 IO.popen(acct.sendmail, "w") { |p| write_full_message_to p, date, false }
210 raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
211 SentManager.write_sent_message(date, from_email) { |f| write_full_message_to f, date, true }
212 BufferManager.kill_buffer buffer
213 BufferManager.flash "Message sent!"
215 rescue SystemCallError, SendmailCommandFailed => e
216 Redwood::log "Problem sending mail: #{e.message}"
217 BufferManager.flash "Problem sending mail: #{e.message}"
223 DraftManager.write_draft { |f| write_message f, false }
224 BufferManager.kill_buffer buffer
225 BufferManager.flash "Saved for later editing."
228 def write_full_message_to f, date=Time.now, escape=false
229 m = RMail::Message.new
230 @header.each do |k, v|
231 next if v.nil? || v.empty?
241 m.header["Date"] = date.rfc2822
242 m.header["Message-Id"] = @message_id
243 m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
245 if @attachments.empty?
246 m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
248 m.body = sanitize_body m.body if escape
249 m.body += sig_lines.join("\n") unless $config[:edit_signature]
251 body_m = RMail::Message.new
252 body_m.body = @body.join
253 body_m.body = sanitize_body body_m.body if escape
254 body_m.body += sig_lines.join("\n") unless $config[:edit_signature]
255 body_m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
256 body_m.header["Content-Disposition"] = "inline"
259 @attachments.each { |fn| m.add_file_attachment fn.to_s }
264 ## TODO: remove this. redundant with write_full_message_to.
266 ## this is going to change soon: draft messages (currently written
267 ## with full=false) will be output as yaml.
268 def write_message f, full=true, date=Time.now
269 raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
270 f.puts format_headers(@header).first
272 Date: #{date.rfc2822}
273 Message-Id: #{@message_id}
278 Content-Type: text/plain; charset=us-ascii
279 Content-Disposition: inline
280 User-Agent: Redwood/#{Redwood::VERSION}
285 f.puts sanitize_body(@body.join)
286 f.puts sig_lines if full unless $config[:edit_signature]
294 text = BufferManager.ask :subject, "Subject: ", @header[field]
296 @header[field] = parse_header field, text
304 @header[field].join(", ")
309 contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
311 text = contacts.map { |s| s.longname }.join(", ")
312 @header[field] = parse_header field, text
321 def sanitize_body body
322 body.gsub(/^From /, ">From ")
325 def mentions_attachments?
326 @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
330 @body.join =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
334 p = PersonManager.person_for(@header["From"])
335 from_email = p && p.email
337 ## first run the hook
338 hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
339 return ["", "-- "] + hook_sig.split("\n") if hook_sig
341 ## no hook, do default signature generation based on config.yaml
342 return [] unless from_email
343 sigfn = (AccountManager.account_for(from_email) ||
344 AccountManager.default_account).signature
346 if sigfn && File.exists?(sigfn)
347 ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }