You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mail_handler.rb 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2017 Jean-Philippe Lang
  3. #
  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.
  8. #
  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.
  13. #
  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.
  17. class MailHandler < ActionMailer::Base
  18. include ActionView::Helpers::SanitizeHelper
  19. include Redmine::I18n
  20. class UnauthorizedAction < StandardError; end
  21. class MissingInformation < StandardError; end
  22. attr_reader :email, :user, :handler_options
  23. def self.receive(raw_mail, options={})
  24. options = options.deep_dup
  25. options[:issue] ||= {}
  26. options[:allow_override] ||= []
  27. if options[:allow_override].is_a?(String)
  28. options[:allow_override] = options[:allow_override].split(',')
  29. end
  30. options[:allow_override].map! {|s| s.strip.downcase.gsub(/\s+/, '_')}
  31. # Project needs to be overridable if not specified
  32. options[:allow_override] << 'project' unless options[:issue].has_key?(:project)
  33. options[:no_account_notice] = (options[:no_account_notice].to_s == '1')
  34. options[:no_notification] = (options[:no_notification].to_s == '1')
  35. options[:no_permission_check] = (options[:no_permission_check].to_s == '1')
  36. raw_mail.force_encoding('ASCII-8BIT')
  37. ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
  38. mail = Mail.new(raw_mail)
  39. set_payload_for_mail(payload, mail)
  40. new.receive(mail, options)
  41. end
  42. end
  43. # Receives an email and rescues any exception
  44. def self.safe_receive(*args)
  45. receive(*args)
  46. rescue Exception => e
  47. logger.error "MailHandler: an unexpected error occurred when receiving email: #{e.message}" if logger
  48. return false
  49. end
  50. # Extracts MailHandler options from environment variables
  51. # Use when receiving emails with rake tasks
  52. def self.extract_options_from_env(env)
  53. options = {:issue => {}}
  54. %w(project status tracker category priority assigned_to fixed_version).each do |option|
  55. options[:issue][option.to_sym] = env[option] if env[option]
  56. end
  57. %w(allow_override unknown_user no_permission_check no_account_notice no_notification default_group project_from_subaddress).each do |option|
  58. options[option.to_sym] = env[option] if env[option]
  59. end
  60. if env['private']
  61. options[:issue][:is_private] = '1'
  62. end
  63. options
  64. end
  65. def logger
  66. Rails.logger
  67. end
  68. cattr_accessor :ignored_emails_headers
  69. self.ignored_emails_headers = {
  70. 'Auto-Submitted' => /\Aauto-(replied|generated)/,
  71. 'X-Autoreply' => 'yes'
  72. }
  73. # Processes incoming emails
  74. # Returns the created object (eg. an issue, a message) or false
  75. def receive(email, options={})
  76. @email = email
  77. @handler_options = options
  78. sender_email = email.from.to_a.first.to_s.strip
  79. # Ignore emails received from the application emission address to avoid hell cycles
  80. if sender_email.casecmp(Setting.mail_from.to_s.strip) == 0
  81. if logger
  82. logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
  83. end
  84. return false
  85. end
  86. # Ignore auto generated emails
  87. self.class.ignored_emails_headers.each do |key, ignored_value|
  88. value = email.header[key]
  89. if value
  90. value = value.to_s.downcase
  91. if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
  92. if logger
  93. logger.info "MailHandler: ignoring email with #{key}:#{value} header"
  94. end
  95. return false
  96. end
  97. end
  98. end
  99. @user = User.find_by_mail(sender_email) if sender_email.present?
  100. if @user && !@user.active?
  101. if logger
  102. logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
  103. end
  104. return false
  105. end
  106. if @user.nil?
  107. # Email was submitted by an unknown user
  108. case handler_options[:unknown_user]
  109. when 'accept'
  110. @user = User.anonymous
  111. when 'create'
  112. @user = create_user_from_email
  113. if @user
  114. if logger
  115. logger.info "MailHandler: [#{@user.login}] account created"
  116. end
  117. add_user_to_group(handler_options[:default_group])
  118. unless handler_options[:no_account_notice]
  119. ::Mailer.deliver_account_information(@user, @user.password)
  120. end
  121. else
  122. if logger
  123. logger.error "MailHandler: could not create account for [#{sender_email}]"
  124. end
  125. return false
  126. end
  127. else
  128. # Default behaviour, emails from unknown users are ignored
  129. if logger
  130. logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
  131. end
  132. return false
  133. end
  134. end
  135. User.current = @user
  136. dispatch
  137. end
  138. private
  139. MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+(\.[a-f0-9]+)?@}
  140. ISSUE_REPLY_SUBJECT_RE = %r{\[(?:[^\]]*\s+)?#(\d+)\]}
  141. MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
  142. def dispatch
  143. headers = [email.in_reply_to, email.references].flatten.compact
  144. subject = email.subject.to_s
  145. if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
  146. klass, object_id = $1, $2.to_i
  147. method_name = "receive_#{klass}_reply"
  148. if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
  149. send method_name, object_id
  150. else
  151. # ignoring it
  152. end
  153. elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
  154. receive_issue_reply(m[1].to_i)
  155. elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
  156. receive_message_reply(m[1].to_i)
  157. else
  158. dispatch_to_default
  159. end
  160. rescue ActiveRecord::RecordInvalid => e
  161. # TODO: send a email to the user
  162. logger.error "MailHandler: #{e.message}" if logger
  163. false
  164. rescue MissingInformation => e
  165. logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
  166. false
  167. rescue UnauthorizedAction => e
  168. logger.error "MailHandler: unauthorized attempt from #{user}" if logger
  169. false
  170. end
  171. def dispatch_to_default
  172. receive_issue
  173. end
  174. # Creates a new issue
  175. def receive_issue
  176. project = target_project
  177. # check permission
  178. unless handler_options[:no_permission_check]
  179. raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
  180. end
  181. issue = Issue.new(:author => user, :project => project)
  182. attributes = issue_attributes_from_keywords(issue)
  183. if handler_options[:no_permission_check]
  184. issue.tracker_id = attributes['tracker_id']
  185. if project
  186. issue.tracker_id ||= project.trackers.first.try(:id)
  187. end
  188. end
  189. issue.safe_attributes = attributes
  190. issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
  191. issue.subject = cleaned_up_subject
  192. if issue.subject.blank?
  193. issue.subject = '(no subject)'
  194. end
  195. issue.description = cleaned_up_text_body
  196. issue.start_date ||= User.current.today if Setting.default_issue_start_date_to_creation_date?
  197. issue.is_private = (handler_options[:issue][:is_private] == '1')
  198. # add To and Cc as watchers before saving so the watchers can reply to Redmine
  199. add_watchers(issue)
  200. issue.save!
  201. add_attachments(issue)
  202. logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger
  203. issue
  204. end
  205. # Adds a note to an existing issue
  206. def receive_issue_reply(issue_id, from_journal=nil)
  207. issue = Issue.find_by_id(issue_id)
  208. return unless issue
  209. # check permission
  210. unless handler_options[:no_permission_check]
  211. unless user.allowed_to?(:add_issue_notes, issue.project) ||
  212. user.allowed_to?(:edit_issues, issue.project)
  213. raise UnauthorizedAction
  214. end
  215. end
  216. # ignore CLI-supplied defaults for new issues
  217. handler_options[:issue] = {}
  218. journal = issue.init_journal(user)
  219. if from_journal && from_journal.private_notes?
  220. # If the received email was a reply to a private note, make the added note private
  221. issue.private_notes = true
  222. end
  223. issue.safe_attributes = issue_attributes_from_keywords(issue)
  224. issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
  225. journal.notes = cleaned_up_text_body
  226. # add To and Cc as watchers before saving so the watchers can reply to Redmine
  227. add_watchers(issue)
  228. issue.save!
  229. add_attachments(issue)
  230. if logger
  231. logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
  232. end
  233. journal
  234. end
  235. # Reply will be added to the issue
  236. def receive_journal_reply(journal_id)
  237. journal = Journal.find_by_id(journal_id)
  238. if journal && journal.journalized_type == 'Issue'
  239. receive_issue_reply(journal.journalized_id, journal)
  240. end
  241. end
  242. # Receives a reply to a forum message
  243. def receive_message_reply(message_id)
  244. message = Message.find_by_id(message_id)
  245. if message
  246. message = message.root
  247. unless handler_options[:no_permission_check]
  248. raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
  249. end
  250. if !message.locked?
  251. reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
  252. :content => cleaned_up_text_body)
  253. reply.author = user
  254. reply.board = message.board
  255. message.children << reply
  256. add_attachments(reply)
  257. reply
  258. else
  259. if logger
  260. logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
  261. end
  262. end
  263. end
  264. end
  265. def add_attachments(obj)
  266. if email.attachments && email.attachments.any?
  267. email.attachments.each do |attachment|
  268. next unless accept_attachment?(attachment)
  269. next unless attachment.body.decoded.size > 0
  270. obj.attachments << Attachment.create(:container => obj,
  271. :file => attachment.body.decoded,
  272. :filename => attachment.filename,
  273. :author => user,
  274. :content_type => attachment.mime_type)
  275. end
  276. end
  277. end
  278. # Returns false if the +attachment+ of the incoming email should be ignored
  279. def accept_attachment?(attachment)
  280. @excluded ||= Setting.mail_handler_excluded_filenames.to_s.split(',').map(&:strip).reject(&:blank?)
  281. @excluded.each do |pattern|
  282. if Setting.mail_handler_enable_regex_excluded_filenames?
  283. regexp = %r{\A#{pattern}\z}i
  284. else
  285. regexp = %r{\A#{Regexp.escape(pattern).gsub("\\*", ".*")}\z}i
  286. end
  287. if attachment.filename.to_s =~ regexp
  288. logger.info "MailHandler: ignoring attachment #{attachment.filename} matching #{pattern}"
  289. return false
  290. end
  291. end
  292. true
  293. end
  294. # Adds To and Cc as watchers of the given object if the sender has the
  295. # appropriate permission
  296. def add_watchers(obj)
  297. if handler_options[:no_permission_check] || user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
  298. addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
  299. unless addresses.empty?
  300. users = User.active.having_mail(addresses).to_a
  301. users -= obj.watcher_users
  302. users.each do |u|
  303. obj.add_watcher(u)
  304. end
  305. end
  306. end
  307. end
  308. def get_keyword(attr, options={})
  309. @keywords ||= {}
  310. if @keywords.has_key?(attr)
  311. @keywords[attr]
  312. else
  313. @keywords[attr] = begin
  314. override = options.key?(:override) ?
  315. options[:override] :
  316. (handler_options[:allow_override] & [attr.to_s.downcase.gsub(/\s+/, '_'), 'all']).present?
  317. if override && (v = extract_keyword!(cleaned_up_text_body, attr, options[:format]))
  318. v
  319. elsif !handler_options[:issue][attr].blank?
  320. handler_options[:issue][attr]
  321. end
  322. end
  323. end
  324. end
  325. # Destructively extracts the value for +attr+ in +text+
  326. # Returns nil if no matching keyword found
  327. def extract_keyword!(text, attr, format=nil)
  328. keys = [attr.to_s.humanize]
  329. if attr.is_a?(Symbol)
  330. if user && user.language.present?
  331. keys << l("field_#{attr}", :default => '', :locale => user.language)
  332. end
  333. if Setting.default_language.present?
  334. keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
  335. end
  336. end
  337. keys.reject! {|k| k.blank?}
  338. keys.collect! {|k| Regexp.escape(k)}
  339. format ||= '.+'
  340. keyword = nil
  341. regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
  342. if m = text.match(regexp)
  343. keyword = m[2].strip
  344. text.sub!(regexp, '')
  345. end
  346. keyword
  347. end
  348. def get_project_from_receiver_addresses
  349. local, domain = handler_options[:project_from_subaddress].to_s.split("@")
  350. return nil unless local && domain
  351. local = Regexp.escape(local)
  352. [:to, :cc, :bcc].each do |field|
  353. header = @email[field]
  354. next if header.blank? || header.field.blank? || !header.field.respond_to?(:addrs)
  355. header.field.addrs.each do |addr|
  356. if addr.domain.to_s.casecmp(domain)==0 && addr.local.to_s =~ /\A#{local}\+([^+]+)\z/
  357. if project = Project.find_by_identifier($1)
  358. return project
  359. end
  360. end
  361. end
  362. end
  363. nil
  364. end
  365. def target_project
  366. # TODO: other ways to specify project:
  367. # * parse the email To field
  368. # * specific project (eg. Setting.mail_handler_target_project)
  369. target = get_project_from_receiver_addresses
  370. target ||= Project.find_by_identifier(get_keyword(:project))
  371. if target.nil?
  372. # Invalid project keyword, use the project specified as the default one
  373. default_project = handler_options[:issue][:project]
  374. if default_project.present?
  375. target = Project.find_by_identifier(default_project)
  376. end
  377. end
  378. raise MissingInformation.new('Unable to determine target project') if target.nil?
  379. target
  380. end
  381. # Returns a Hash of issue attributes extracted from keywords in the email body
  382. def issue_attributes_from_keywords(issue)
  383. attrs = {
  384. 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
  385. 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
  386. 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
  387. 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
  388. 'assigned_to_id' => (k = get_keyword(:assigned_to)) && find_assignee_from_keyword(k, issue).try(:id),
  389. 'fixed_version_id' => (k = get_keyword(:fixed_version)) && issue.project.shared_versions.named(k).first.try(:id),
  390. 'start_date' => get_keyword(:start_date, :format => '\d{4}-\d{2}-\d{2}'),
  391. 'due_date' => get_keyword(:due_date, :format => '\d{4}-\d{2}-\d{2}'),
  392. 'estimated_hours' => get_keyword(:estimated_hours),
  393. 'done_ratio' => get_keyword(:done_ratio, :format => '(\d|10)?0'),
  394. 'parent_issue_id' => get_keyword(:parent_issue)
  395. }.delete_if {|k, v| v.blank? }
  396. attrs
  397. end
  398. # Returns a Hash of issue custom field values extracted from keywords in the email body
  399. def custom_field_values_from_keywords(customized)
  400. customized.custom_field_values.inject({}) do |h, v|
  401. if keyword = get_keyword(v.custom_field.name)
  402. h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
  403. end
  404. h
  405. end
  406. end
  407. # Returns the text/plain part of the email
  408. # If not found (eg. HTML-only email), returns the body with tags removed
  409. def plain_text_body
  410. return @plain_text_body unless @plain_text_body.nil?
  411. # check if we have any plain-text parts with content
  412. @plain_text_body = email_parts_to_text(email.all_parts.select {|p| p.mime_type == 'text/plain'}).presence
  413. # if not, we try to parse the body from the HTML-parts
  414. @plain_text_body ||= email_parts_to_text(email.all_parts.select {|p| p.mime_type == 'text/html'}).presence
  415. # If there is still no body found, and there are no mime-parts defined,
  416. # we use the whole raw mail body
  417. @plain_text_body ||= email_parts_to_text([email]).presence if email.all_parts.empty?
  418. # As a fallback we return an empty plain text body (e.g. if we have only
  419. # empty text parts but a non-text attachment)
  420. @plain_text_body ||= ""
  421. end
  422. def email_parts_to_text(parts)
  423. parts.reject! do |part|
  424. part.attachment?
  425. end
  426. parts.map do |p|
  427. body_charset = Mail::RubyVer.respond_to?(:pick_encoding) ?
  428. Mail::RubyVer.pick_encoding(p.charset).to_s : p.charset
  429. body = Redmine::CodesetUtil.to_utf8(p.body.decoded, body_charset)
  430. # convert html parts to text
  431. p.mime_type == 'text/html' ? self.class.html_body_to_text(body) : self.class.plain_text_body_to_text(body)
  432. end.join("\r\n")
  433. end
  434. def cleaned_up_text_body
  435. @cleaned_up_text_body ||= cleanup_body(plain_text_body)
  436. end
  437. def cleaned_up_subject
  438. subject = email.subject.to_s
  439. subject.strip[0,255]
  440. end
  441. # Converts a HTML email body to text
  442. def self.html_body_to_text(html)
  443. Redmine::WikiFormatting.html_parser.to_text(html)
  444. end
  445. # Converts a plain/text email body to text
  446. def self.plain_text_body_to_text(text)
  447. # Removes leading spaces that would cause the line to be rendered as
  448. # preformatted text with textile
  449. text.gsub(/^ +(?![*#])/, '')
  450. end
  451. def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
  452. limit ||= object.class.columns_hash[attribute.to_s].limit || 255
  453. value = value.to_s.slice(0, limit)
  454. object.send("#{attribute}=", value)
  455. end
  456. # Returns a User from an email address and a full name
  457. def self.new_user_from_attributes(email_address, fullname=nil)
  458. user = User.new
  459. # Truncating the email address would result in an invalid format
  460. user.mail = email_address
  461. assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
  462. names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
  463. assign_string_attribute_with_limit(user, 'firstname', names.shift, 30)
  464. assign_string_attribute_with_limit(user, 'lastname', names.join(' '), 30)
  465. user.lastname = '-' if user.lastname.blank?
  466. user.language = Setting.default_language
  467. user.generate_password = true
  468. user.mail_notification = 'only_my_events'
  469. unless user.valid?
  470. user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
  471. user.firstname = "-" unless user.errors[:firstname].blank?
  472. (puts user.errors[:lastname];user.lastname = "-") unless user.errors[:lastname].blank?
  473. end
  474. user
  475. end
  476. # Creates a User for the +email+ sender
  477. # Returns the user or nil if it could not be created
  478. def create_user_from_email
  479. from = email.header['from'].to_s
  480. addr, name = from, nil
  481. if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
  482. addr, name = m[2], m[1]
  483. end
  484. if addr.present?
  485. user = self.class.new_user_from_attributes(addr, name)
  486. if handler_options[:no_notification]
  487. user.mail_notification = 'none'
  488. end
  489. if user.save
  490. user
  491. else
  492. logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
  493. nil
  494. end
  495. else
  496. logger.error "MailHandler: failed to create User: no FROM address found" if logger
  497. nil
  498. end
  499. end
  500. # Adds the newly created user to default group
  501. def add_user_to_group(default_group)
  502. if default_group.present?
  503. default_group.split(',').each do |group_name|
  504. if group = Group.named(group_name).first
  505. group.users << @user
  506. elsif logger
  507. logger.warn "MailHandler: could not add user to [#{group_name}], group not found"
  508. end
  509. end
  510. end
  511. end
  512. # Removes the email body of text after the truncation configurations.
  513. def cleanup_body(body)
  514. delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?)
  515. if Setting.mail_handler_enable_regex_delimiters?
  516. begin
  517. delimiters = delimiters.map {|s| Regexp.new(s)}
  518. rescue RegexpError => e
  519. logger.error "MailHandler: invalid regexp delimiter found in mail_handler_body_delimiters setting (#{e.message})" if logger
  520. end
  521. end
  522. unless delimiters.empty?
  523. regex = Regexp.new("^[> ]*(#{ Regexp.union(delimiters) })[[:blank:]]*[\r\n].*", Regexp::MULTILINE)
  524. body = body.gsub(regex, '')
  525. end
  526. body.strip
  527. end
  528. def find_assignee_from_keyword(keyword, issue)
  529. Principal.detect_by_keyword(issue.assignable_users, keyword)
  530. end
  531. end