1 # Redmine - project management software
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 class MailHandler < ActionMailer::Base
19 include ActionView::Helpers::SanitizeHelper
22 class UnauthorizedAction < StandardError; end
23 class MissingInformation < StandardError; end
25 attr_reader :email, :user
27 def self.receive(email, options={})
28 @@handler_options = options.dup
30 @@handler_options[:issue] ||= {}
32 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
33 @@handler_options[:allow_override] ||= []
34 # Project needs to be overridable if not specified
35 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
36 # Status overridable by default
37 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
39 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
43 # Processes incoming emails
44 # Returns the created object (eg. an issue, a message) or false
47 sender_email = email.from.to_a.first.to_s.strip
48 # Ignore emails received from the application emission address to avoid hell cycles
49 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
50 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]" if logger && logger.info
53 @user = User.find_by_mail(sender_email) if sender_email.present?
54 if @user && !@user.active?
55 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]" if logger && logger.info
59 # Email was submitted by an unknown user
60 case @@handler_options[:unknown_user]
62 @user = User.anonymous
64 @user = MailHandler.create_user_from_email(email)
66 logger.info "MailHandler: [#{@user.login}] account created" if logger && logger.info
67 Mailer.deliver_account_information(@user, @user.password)
69 logger.error "MailHandler: could not create account for [#{sender_email}]" if logger && logger.error
73 # Default behaviour, emails from unknown users are ignored
74 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]" if logger && logger.info
84 MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
85 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
86 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
89 headers = [email.in_reply_to, email.references].flatten.compact
90 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
91 klass, object_id = $1, $2.to_i
92 method_name = "receive_#{klass}_reply"
93 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
94 send method_name, object_id
98 elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
99 receive_issue_reply(m[1].to_i)
100 elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
101 receive_message_reply(m[1].to_i)
105 rescue ActiveRecord::RecordInvalid => e
106 # TODO: send a email to the user
107 logger.error e.message if logger
109 rescue MissingInformation => e
110 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
112 rescue UnauthorizedAction => e
113 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
117 def dispatch_to_default
121 # Creates a new issue
123 project = target_project
125 unless @@handler_options[:no_permission_check]
126 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
129 issue = Issue.new(:author => user, :project => project)
130 issue.safe_attributes = issue_attributes_from_keywords(issue)
131 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
132 issue.subject = email.subject.to_s.chomp[0,255]
133 if issue.subject.blank?
134 issue.subject = '(no subject)'
136 issue.description = cleaned_up_text_body
138 # add To and Cc as watchers before saving so the watchers can reply to Redmine
141 add_attachments(issue)
142 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
146 # Adds a note to an existing issue
147 def receive_issue_reply(issue_id)
148 issue = Issue.find_by_id(issue_id)
151 unless @@handler_options[:no_permission_check]
152 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
155 # ignore CLI-supplied defaults for new issues
156 @@handler_options[:issue].clear
158 journal = issue.init_journal(user)
159 issue.safe_attributes = issue_attributes_from_keywords(issue)
160 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
161 journal.notes = cleaned_up_text_body
162 add_attachments(issue)
164 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
168 # Reply will be added to the issue
169 def receive_journal_reply(journal_id)
170 journal = Journal.find_by_id(journal_id)
171 if journal && journal.journalized_type == 'Issue'
172 receive_issue_reply(journal.journalized_id)
176 # Receives a reply to a forum message
177 def receive_message_reply(message_id)
178 message = Message.find_by_id(message_id)
180 message = message.root
182 unless @@handler_options[:no_permission_check]
183 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
187 reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
188 :content => cleaned_up_text_body)
190 reply.board = message.board
191 message.children << reply
192 add_attachments(reply)
195 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic" if logger && logger.info
200 def add_attachments(obj)
201 if email.has_attachments?
202 email.attachments.each do |attachment|
203 Attachment.create(:container => obj,
206 :content_type => attachment.content_type)
211 # Adds To and Cc as watchers of the given object if the sender has the
212 # appropriate permission
213 def add_watchers(obj)
214 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
215 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
216 unless addresses.empty?
217 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
218 watchers.each {|w| obj.add_watcher(w)}
223 def get_keyword(attr, options={})
225 if @keywords.has_key?(attr)
228 @keywords[attr] = begin
229 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && (v = extract_keyword!(plain_text_body, attr, options[:format]))
231 elsif !@@handler_options[:issue][attr].blank?
232 @@handler_options[:issue][attr]
238 # Destructively extracts the value for +attr+ in +text+
239 # Returns nil if no matching keyword found
240 def extract_keyword!(text, attr, format=nil)
241 keys = [attr.to_s.humanize]
242 if attr.is_a?(Symbol)
243 keys << l("field_#{attr}", :default => '', :locale => user.language) if user && user.language.present?
244 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language) if Setting.default_language.present?
246 keys.reject! {|k| k.blank?}
247 keys.collect! {|k| Regexp.escape(k)}
249 text.gsub!(/^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i, '')
254 # TODO: other ways to specify project:
255 # * parse the email To field
256 # * specific project (eg. Setting.mail_handler_target_project)
257 target = Project.find_by_identifier(get_keyword(:project))
258 raise MissingInformation.new('Unable to determine target project') if target.nil?
262 # Returns a Hash of issue attributes extracted from keywords in the email body
263 def issue_attributes_from_keywords(issue)
264 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_user_from_keyword(k)
265 assigned_to = nil if assigned_to && !issue.assignable_users.include?(assigned_to)
268 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.find_by_name(k).try(:id),
269 'status_id' => (k = get_keyword(:status)) && IssueStatus.find_by_name(k).try(:id),
270 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.find_by_name(k).try(:id),
271 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.find_by_name(k).try(:id),
272 'assigned_to_id' => assigned_to.try(:id),
273 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.find_by_name(k).try(:id),
274 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
275 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
276 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
277 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
278 }.delete_if {|k, v| v.blank? }
280 if issue.new_record? && attrs['tracker_id'].nil?
281 attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
287 # Returns a Hash of issue custom field values extracted from keywords in the email body
288 def custom_field_values_from_keywords(customized)
289 customized.custom_field_values.inject({}) do |h, v|
290 if value = get_keyword(v.custom_field.name, :override => true)
291 h[v.custom_field.id.to_s] = value
297 # Returns the text/plain part of the email
298 # If not found (eg. HTML-only email), returns the body with tags removed
300 return @plain_text_body unless @plain_text_body.nil?
301 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
305 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
306 if plain_text_part.nil?
307 # no text/plain part found, assuming html-only email
308 # strip html tags and remove doctype directive
309 @plain_text_body = strip_tags(@email.body.to_s)
310 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
312 @plain_text_body = plain_text_part.body.to_s
314 @plain_text_body.strip!
318 def cleaned_up_text_body
319 cleanup_body(plain_text_body)
322 def self.full_sanitizer
323 @full_sanitizer ||= HTML::FullSanitizer.new
326 # Creates a user account for the +email+ sender
327 def self.create_user_from_email(email)
328 addr = email.from_addrs.to_a.first
329 if addr && !addr.spec.blank?
331 user.mail = addr.spec
333 names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split
334 user.firstname = names.shift
335 user.lastname = names.join(' ')
336 user.lastname = '-' if user.lastname.blank?
338 user.login = user.mail
339 user.password = ActiveSupport::SecureRandom.hex(5)
340 user.language = Setting.default_language
341 user.save ? user : nil
347 # Removes the email body of text after the truncation configurations.
348 def cleanup_body(body)
349 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
350 unless delimiters.empty?
351 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
352 body = body.gsub(regex, '')
357 def find_user_from_keyword(keyword)
358 user ||= User.find_by_mail(keyword)
359 user ||= User.find_by_login(keyword)
360 if user.nil? && keyword.match(/ /)
361 firstname, lastname = *(keyword.split) # "First Last Throwaway"
362 user ||= User.find_by_firstname_and_lastname(firstname, lastname)