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_field, "Edit field", 'e'
34 k.add :edit_message, "Edit message", :enter
35 k.add :save_as_draft, "Save as draft", 'P'
36 k.add :attach_file, "Attach a file", 'a'
37 k.add :delete_attachment, "Delete an attachment", 'd'
40 def initialize opts={}
41 @header = opts.delete(:header) || {}
44 @body = opts.delete(:body) || []
45 @body += sig_lines if $config[:edit_signature]
48 @message_id = "<#{Time.now.to_i}-sup-#{rand 10000}@#{Socket.gethostname}>"
50 @skip_top_rows = opts[:skip_top_rows] || 0
56 def lines; @text.length end
57 def [] i; @text[i] end
60 def handle_new_text header, body; end
63 if (curpos - @skip_top_rows) >= @header_lines.length
66 case(field = @header_lines[curpos - @skip_top_rows])
68 text = BufferManager.ask :subject, "Subject: ", @header[field]
69 @header[field] = parse_header field, text if text
74 @header[field].join(", ")
79 contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
81 text = contacts.map { |s| s.longname }.join(", ")
82 @header[field] = parse_header field, text
90 @file = Tempfile.new "sup.#{self.class.name.gsub(/.*::/, '').camel_to_hyphy}"
91 @file.puts format_headers(@header - NON_EDITABLE_HEADERS).first
96 editor = $config[:editor] || ENV['EDITOR'] || "/usr/bin/vi"
98 mtime = File.mtime @file.path
99 BufferManager.shell_out "#{editor} #{@file.path}"
100 @edited = true if File.mtime(@file.path) > mtime
102 return @edited unless @edited
104 header, @body = parse_file @file.path
105 @header = header - NON_EDITABLE_HEADERS
106 handle_new_text @header, @body
113 !edited? || BufferManager.ask_yes_or_no("Discard message?")
117 fn = BufferManager.ask_for_filename :attachment, "File name (enter for browser): "
119 @attachments << Pathname.new(fn)
123 def delete_attachment
124 i = (curpos - @skip_top_rows) - @attachment_lines_offset
125 if i >= 0 && i < @attachments.size && BufferManager.ask_yes_or_no("Delete attachment #{@attachments[i]}?")
126 @attachments.delete_at i
135 buffer.mark_dirty if buffer
139 header, @header_lines = format_headers(@header - NON_EDITABLE_HEADERS) + [""]
140 @text = header + [""] + @body
141 @text += sig_lines unless $config[:edit_signature]
143 unless @attachments.empty?
145 @attachment_lines_offset = @text.length
146 @text += @attachments.map { |f| [[:attachment_color, "+ Attachment: #{f} (#{f.human_size})"]] }
152 header = MBox::read_header f
155 header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
156 header.each { |k, v| header[k] = parse_header k, v }
162 def parse_header k, v
163 if MULTI_HEADERS.include?(k)
164 v.split_on_commas.map do |name|
165 (p = ContactManager.contact_for(name)) && p.full_address || name
172 def format_headers header
174 headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
175 lines = make_lines "#{h}:", header[h]
176 lines.length.times { header_lines << h }
179 [headers, header_lines]
182 def make_lines header, things
187 [header + " " + things]
192 things.map_with_index do |name, i|
193 raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
197 (" " * (header.length + 1)) + name
198 end + (i == things.length - 1 ? "" : ",")
205 return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
206 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
207 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
211 if @header["From"] =~ /<?(\S+@(\S+?))>?$/
214 AccountManager.default_account.email
217 acct = AccountManager.account_for(from_email) || AccountManager.default_account
218 BufferManager.flash "Sending..."
221 IO.popen(acct.sendmail, "w") { |p| write_full_message_to p, date, false }
222 raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
223 SentManager.write_sent_message(date, from_email) { |f| write_full_message_to f, date, true }
224 BufferManager.kill_buffer buffer
225 BufferManager.flash "Message sent!"
227 rescue SystemCallError, SendmailCommandFailed => e
228 Redwood::log "Problem sending mail: #{e.message}"
229 BufferManager.flash "Problem sending mail: #{e.message}"
235 DraftManager.write_draft { |f| write_message f, false }
236 BufferManager.kill_buffer buffer
237 BufferManager.flash "Saved for later editing."
240 def write_full_message_to f, date=Time.now, escape=false
241 m = RMail::Message.new
242 @header.each do |k, v|
243 next if v.nil? || v.empty?
253 m.header["Date"] = date.rfc2822
254 m.header["Message-Id"] = @message_id
255 m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
257 if @attachments.empty?
258 m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
260 m.body = sanitize_body m.body if escape
261 m.body += sig_lines.join("\n") unless $config[:edit_signature]
263 body_m = RMail::Message.new
264 body_m.body = @body.join
265 body_m.body = sanitize_body body_m.body if escape
266 body_m.body += sig_lines.join("\n") unless $config[:edit_signature]
267 body_m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
268 body_m.header["Content-Disposition"] = "inline"
271 @attachments.each { |fn| m.add_file_attachment fn.to_s }
276 ## TODO: remove this. redundant with write_full_message_to.
278 ## this is going to change soon: draft messages (currently written
279 ## with full=false) will be output as yaml.
280 def write_message f, full=true, date=Time.now
281 raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
282 f.puts format_headers(@header).first
284 Date: #{date.rfc2822}
285 Message-Id: #{@message_id}
290 Content-Type: text/plain; charset=us-ascii
291 Content-Disposition: inline
292 User-Agent: Redwood/#{Redwood::VERSION}
297 f.puts sanitize_body(@body.join)
298 f.puts sig_lines if full unless $config[:edit_signature]
303 def sanitize_body body
304 body.gsub(/^From /, ">From ")
307 def mentions_attachments?
308 @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
312 @body.join =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
316 p = PersonManager.person_for(@header["From"])
317 from_email = p && p.email
319 ## first run the hook
320 hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
321 return ["", "-- "] + hook_sig.split("\n") if hook_sig
323 ## no hook, do default signature generation based on config.yaml
324 return [] unless from_email
325 sigfn = (AccountManager.account_for(from_email) ||
326 AccountManager.default_account).signature
328 if sigfn && File.exists?(sigfn)
329 ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }