##// END OF EJS Templates
Use In-Reply-To and References headers to handle replies by email....
Jean-Philippe Lang -
r2286:0c4e40b89cfe
parent child
Show More
@@ -1,192 +1,211
1 # redMine - project management software
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
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
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.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class MailHandler < ActionMailer::Base
18 class MailHandler < ActionMailer::Base
19 include ActionView::Helpers::SanitizeHelper
19 include ActionView::Helpers::SanitizeHelper
20
20
21 class UnauthorizedAction < StandardError; end
21 class UnauthorizedAction < StandardError; end
22 class MissingInformation < StandardError; end
22 class MissingInformation < StandardError; end
23
23
24 attr_reader :email, :user
24 attr_reader :email, :user
25
25
26 def self.receive(email, options={})
26 def self.receive(email, options={})
27 @@handler_options = options.dup
27 @@handler_options = options.dup
28
28
29 @@handler_options[:issue] ||= {}
29 @@handler_options[:issue] ||= {}
30
30
31 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
31 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
32 @@handler_options[:allow_override] ||= []
32 @@handler_options[:allow_override] ||= []
33 # Project needs to be overridable if not specified
33 # Project needs to be overridable if not specified
34 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
34 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
35 # Status overridable by default
35 # Status overridable by default
36 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
36 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
37 super email
37 super email
38 end
38 end
39
39
40 # Processes incoming emails
40 # Processes incoming emails
41 def receive(email)
41 def receive(email)
42 @email = email
42 @email = email
43 @user = User.active.find_by_mail(email.from.first.to_s.strip)
43 @user = User.active.find_by_mail(email.from.first.to_s.strip)
44 unless @user
44 unless @user
45 # Unknown user => the email is ignored
45 # Unknown user => the email is ignored
46 # TODO: ability to create the user's account
46 # TODO: ability to create the user's account
47 logger.info "MailHandler: email submitted by unknown user [#{email.from.first}]" if logger && logger.info
47 logger.info "MailHandler: email submitted by unknown user [#{email.from.first}]" if logger && logger.info
48 return false
48 return false
49 end
49 end
50 User.current = @user
50 User.current = @user
51 dispatch
51 dispatch
52 end
52 end
53
53
54 private
54 private
55
55
56 MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
56 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]+#(\d+)\]}
57 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]+#(\d+)\]}
57
58
58 def dispatch
59 def dispatch
59 if m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
60 headers = [email.in_reply_to, email.references].flatten.compact
60 receive_issue_update(m[1].to_i)
61 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
62 klass, object_id = $1, $2.to_i
63 method_name = "receive_#{klass}_reply"
64 if self.class.private_instance_methods.include?(method_name)
65 send method_name, object_id
66 else
67 # ignoring it
68 end
69 elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
70 # for compatibility
71 receive_issue_reply(m[1].to_i)
61 else
72 else
62 receive_issue
73 receive_issue
63 end
74 end
64 rescue ActiveRecord::RecordInvalid => e
75 rescue ActiveRecord::RecordInvalid => e
65 # TODO: send a email to the user
76 # TODO: send a email to the user
66 logger.error e.message if logger
77 logger.error e.message if logger
67 false
78 false
68 rescue MissingInformation => e
79 rescue MissingInformation => e
69 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
80 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
70 false
81 false
71 rescue UnauthorizedAction => e
82 rescue UnauthorizedAction => e
72 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
83 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
73 false
84 false
74 end
85 end
75
86
76 # Creates a new issue
87 # Creates a new issue
77 def receive_issue
88 def receive_issue
78 project = target_project
89 project = target_project
79 tracker = (get_keyword(:tracker) && project.trackers.find_by_name(get_keyword(:tracker))) || project.trackers.find(:first)
90 tracker = (get_keyword(:tracker) && project.trackers.find_by_name(get_keyword(:tracker))) || project.trackers.find(:first)
80 category = (get_keyword(:category) && project.issue_categories.find_by_name(get_keyword(:category)))
91 category = (get_keyword(:category) && project.issue_categories.find_by_name(get_keyword(:category)))
81 priority = (get_keyword(:priority) && Enumeration.find_by_opt_and_name('IPRI', get_keyword(:priority)))
92 priority = (get_keyword(:priority) && Enumeration.find_by_opt_and_name('IPRI', get_keyword(:priority)))
82 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
93 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
83
94
84 # check permission
95 # check permission
85 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
96 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
86 issue = Issue.new(:author => user, :project => project, :tracker => tracker, :category => category, :priority => priority)
97 issue = Issue.new(:author => user, :project => project, :tracker => tracker, :category => category, :priority => priority)
87 # check workflow
98 # check workflow
88 if status && issue.new_statuses_allowed_to(user).include?(status)
99 if status && issue.new_statuses_allowed_to(user).include?(status)
89 issue.status = status
100 issue.status = status
90 end
101 end
91 issue.subject = email.subject.chomp.toutf8
102 issue.subject = email.subject.chomp.toutf8
92 issue.description = plain_text_body
103 issue.description = plain_text_body
93 # custom fields
104 # custom fields
94 issue.custom_field_values = issue.available_custom_fields.inject({}) do |h, c|
105 issue.custom_field_values = issue.available_custom_fields.inject({}) do |h, c|
95 if value = get_keyword(c.name, :override => true)
106 if value = get_keyword(c.name, :override => true)
96 h[c.id] = value
107 h[c.id] = value
97 end
108 end
98 h
109 h
99 end
110 end
100 issue.save!
111 issue.save!
101 add_attachments(issue)
112 add_attachments(issue)
102 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
113 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
103 # add To and Cc as watchers
114 # add To and Cc as watchers
104 add_watchers(issue)
115 add_watchers(issue)
105 # send notification after adding watchers so that they can reply to Redmine
116 # send notification after adding watchers so that they can reply to Redmine
106 Mailer.deliver_issue_add(issue) if Setting.notified_events.include?('issue_added')
117 Mailer.deliver_issue_add(issue) if Setting.notified_events.include?('issue_added')
107 issue
118 issue
108 end
119 end
109
120
110 def target_project
121 def target_project
111 # TODO: other ways to specify project:
122 # TODO: other ways to specify project:
112 # * parse the email To field
123 # * parse the email To field
113 # * specific project (eg. Setting.mail_handler_target_project)
124 # * specific project (eg. Setting.mail_handler_target_project)
114 target = Project.find_by_identifier(get_keyword(:project))
125 target = Project.find_by_identifier(get_keyword(:project))
115 raise MissingInformation.new('Unable to determine target project') if target.nil?
126 raise MissingInformation.new('Unable to determine target project') if target.nil?
116 target
127 target
117 end
128 end
118
129
119 # Adds a note to an existing issue
130 # Adds a note to an existing issue
120 def receive_issue_update(issue_id)
131 def receive_issue_reply(issue_id)
121 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
132 status = (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
122
133
123 issue = Issue.find_by_id(issue_id)
134 issue = Issue.find_by_id(issue_id)
124 return unless issue
135 return unless issue
125 # check permission
136 # check permission
126 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
137 raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
127 raise UnauthorizedAction unless status.nil? || user.allowed_to?(:edit_issues, issue.project)
138 raise UnauthorizedAction unless status.nil? || user.allowed_to?(:edit_issues, issue.project)
128
139
129 # add the note
140 # add the note
130 journal = issue.init_journal(user, plain_text_body)
141 journal = issue.init_journal(user, plain_text_body)
131 add_attachments(issue)
142 add_attachments(issue)
132 # check workflow
143 # check workflow
133 if status && issue.new_statuses_allowed_to(user).include?(status)
144 if status && issue.new_statuses_allowed_to(user).include?(status)
134 issue.status = status
145 issue.status = status
135 end
146 end
136 issue.save!
147 issue.save!
137 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
148 logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
138 Mailer.deliver_issue_edit(journal) if Setting.notified_events.include?('issue_updated')
149 Mailer.deliver_issue_edit(journal) if Setting.notified_events.include?('issue_updated')
139 journal
150 journal
140 end
151 end
141
152
153 # Reply will be added to the issue
154 def receive_journal_reply(journal_id)
155 journal = Journal.find_by_id(journal_id)
156 if journal && journal.journalized_type == 'Issue'
157 receive_issue_reply(journal.journalized_id)
158 end
159 end
160
142 def add_attachments(obj)
161 def add_attachments(obj)
143 if email.has_attachments?
162 if email.has_attachments?
144 email.attachments.each do |attachment|
163 email.attachments.each do |attachment|
145 Attachment.create(:container => obj,
164 Attachment.create(:container => obj,
146 :file => attachment,
165 :file => attachment,
147 :author => user,
166 :author => user,
148 :content_type => attachment.content_type)
167 :content_type => attachment.content_type)
149 end
168 end
150 end
169 end
151 end
170 end
152
171
153 # Adds To and Cc as watchers of the given object if the sender has the
172 # Adds To and Cc as watchers of the given object if the sender has the
154 # appropriate permission
173 # appropriate permission
155 def add_watchers(obj)
174 def add_watchers(obj)
156 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
175 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
157 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
176 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
158 unless addresses.empty?
177 unless addresses.empty?
159 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
178 watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
160 watchers.each {|w| obj.add_watcher(w)}
179 watchers.each {|w| obj.add_watcher(w)}
161 end
180 end
162 end
181 end
163 end
182 end
164
183
165 def get_keyword(attr, options={})
184 def get_keyword(attr, options={})
166 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && plain_text_body =~ /^#{attr}:[ \t]*(.+)$/i
185 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && plain_text_body =~ /^#{attr}:[ \t]*(.+)$/i
167 $1.strip
186 $1.strip
168 elsif !@@handler_options[:issue][attr].blank?
187 elsif !@@handler_options[:issue][attr].blank?
169 @@handler_options[:issue][attr]
188 @@handler_options[:issue][attr]
170 end
189 end
171 end
190 end
172
191
173 # Returns the text/plain part of the email
192 # Returns the text/plain part of the email
174 # If not found (eg. HTML-only email), returns the body with tags removed
193 # If not found (eg. HTML-only email), returns the body with tags removed
175 def plain_text_body
194 def plain_text_body
176 return @plain_text_body unless @plain_text_body.nil?
195 return @plain_text_body unless @plain_text_body.nil?
177 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
196 parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
178 if parts.empty?
197 if parts.empty?
179 parts << @email
198 parts << @email
180 end
199 end
181 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
200 plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
182 if plain_text_part.nil?
201 if plain_text_part.nil?
183 # no text/plain part found, assuming html-only email
202 # no text/plain part found, assuming html-only email
184 # strip html tags and remove doctype directive
203 # strip html tags and remove doctype directive
185 @plain_text_body = strip_tags(@email.body.to_s)
204 @plain_text_body = strip_tags(@email.body.to_s)
186 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
205 @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
187 else
206 else
188 @plain_text_body = plain_text_part.body.to_s
207 @plain_text_body = plain_text_part.body.to_s
189 end
208 end
190 @plain_text_body.strip!
209 @plain_text_body.strip!
191 end
210 end
192 end
211 end
@@ -1,73 +1,74
1 Return-Path: <jsmith@somenet.foo>
1 Return-Path: <jsmith@somenet.foo>
2 Received: from osiris ([127.0.0.1])
2 Received: from osiris ([127.0.0.1])
3 by OSIRIS
3 by OSIRIS
4 with hMailServer ; Sat, 21 Jun 2008 18:41:39 +0200
4 with hMailServer ; Sat, 21 Jun 2008 18:41:39 +0200
5 Message-ID: <006a01c8d3bd$ad9baec0$0a00a8c0@osiris>
5 Message-ID: <006a01c8d3bd$ad9baec0$0a00a8c0@osiris>
6 In-Reply-To: <redmine.issue-2.20060719210421@osiris>
6 From: "John Smith" <jsmith@somenet.foo>
7 From: "John Smith" <jsmith@somenet.foo>
7 To: <redmine@somenet.foo>
8 To: <redmine@somenet.foo>
8 References: <485d0ad366c88_d7014663a025f@osiris.tmail>
9 References: <485d0ad366c88_d7014663a025f@osiris.tmail>
9 Subject: Re: [Cookbook - Feature #2] (New) Add ingredients categories
10 Subject: Re: Add ingredients categories
10 Date: Sat, 21 Jun 2008 18:41:39 +0200
11 Date: Sat, 21 Jun 2008 18:41:39 +0200
11 MIME-Version: 1.0
12 MIME-Version: 1.0
12 Content-Type: multipart/alternative;
13 Content-Type: multipart/alternative;
13 boundary="----=_NextPart_000_0067_01C8D3CE.711F9CC0"
14 boundary="----=_NextPart_000_0067_01C8D3CE.711F9CC0"
14 X-Priority: 3
15 X-Priority: 3
15 X-MSMail-Priority: Normal
16 X-MSMail-Priority: Normal
16 X-Mailer: Microsoft Outlook Express 6.00.2900.2869
17 X-Mailer: Microsoft Outlook Express 6.00.2900.2869
17 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2869
18 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2869
18
19
19 This is a multi-part message in MIME format.
20 This is a multi-part message in MIME format.
20
21
21 ------=_NextPart_000_0067_01C8D3CE.711F9CC0
22 ------=_NextPart_000_0067_01C8D3CE.711F9CC0
22 Content-Type: text/plain;
23 Content-Type: text/plain;
23 charset="utf-8"
24 charset="utf-8"
24 Content-Transfer-Encoding: quoted-printable
25 Content-Transfer-Encoding: quoted-printable
25
26
26 This is reply
27 This is reply
27 ------=_NextPart_000_0067_01C8D3CE.711F9CC0
28 ------=_NextPart_000_0067_01C8D3CE.711F9CC0
28 Content-Type: text/html;
29 Content-Type: text/html;
29 charset="utf-8"
30 charset="utf-8"
30 Content-Transfer-Encoding: quoted-printable
31 Content-Transfer-Encoding: quoted-printable
31
32
32 =EF=BB=BF<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
33 =EF=BB=BF<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
33 <HTML><HEAD>
34 <HTML><HEAD>
34 <META http-equiv=3DContent-Type content=3D"text/html; charset=3Dutf-8">
35 <META http-equiv=3DContent-Type content=3D"text/html; charset=3Dutf-8">
35 <STYLE>BODY {
36 <STYLE>BODY {
36 FONT-SIZE: 0.8em; COLOR: #484848; FONT-FAMILY: Verdana, sans-serif
37 FONT-SIZE: 0.8em; COLOR: #484848; FONT-FAMILY: Verdana, sans-serif
37 }
38 }
38 BODY H1 {
39 BODY H1 {
39 FONT-SIZE: 1.2em; MARGIN: 0px; FONT-FAMILY: "Trebuchet MS", Verdana, =
40 FONT-SIZE: 1.2em; MARGIN: 0px; FONT-FAMILY: "Trebuchet MS", Verdana, =
40 sans-serif
41 sans-serif
41 }
42 }
42 A {
43 A {
43 COLOR: #2a5685
44 COLOR: #2a5685
44 }
45 }
45 A:link {
46 A:link {
46 COLOR: #2a5685
47 COLOR: #2a5685
47 }
48 }
48 A:visited {
49 A:visited {
49 COLOR: #2a5685
50 COLOR: #2a5685
50 }
51 }
51 A:hover {
52 A:hover {
52 COLOR: #c61a1a
53 COLOR: #c61a1a
53 }
54 }
54 A:active {
55 A:active {
55 COLOR: #c61a1a
56 COLOR: #c61a1a
56 }
57 }
57 HR {
58 HR {
58 BORDER-RIGHT: 0px; BORDER-TOP: 0px; BACKGROUND: #ccc; BORDER-LEFT: 0px; =
59 BORDER-RIGHT: 0px; BORDER-TOP: 0px; BACKGROUND: #ccc; BORDER-LEFT: 0px; =
59 WIDTH: 100%; BORDER-BOTTOM: 0px; HEIGHT: 1px
60 WIDTH: 100%; BORDER-BOTTOM: 0px; HEIGHT: 1px
60 }
61 }
61 .footer {
62 .footer {
62 FONT-SIZE: 0.8em; FONT-STYLE: italic
63 FONT-SIZE: 0.8em; FONT-STYLE: italic
63 }
64 }
64 </STYLE>
65 </STYLE>
65
66
66 <META content=3D"MSHTML 6.00.2900.2883" name=3DGENERATOR></HEAD>
67 <META content=3D"MSHTML 6.00.2900.2883" name=3DGENERATOR></HEAD>
67 <BODY bgColor=3D#ffffff>
68 <BODY bgColor=3D#ffffff>
68 <DIV><SPAN class=3Dfooter><FONT face=3DArial color=3D#000000 =
69 <DIV><SPAN class=3Dfooter><FONT face=3DArial color=3D#000000 =
69 size=3D2>This is=20
70 size=3D2>This is=20
70 reply</FONT></DIV></SPAN></BODY></HTML>
71 reply</FONT></DIV></SPAN></BODY></HTML>
71
72
72 ------=_NextPart_000_0067_01C8D3CE.711F9CC0--
73 ------=_NextPart_000_0067_01C8D3CE.711F9CC0--
73
74
General Comments 0
You need to be logged in to leave comments. Login now