Project

General

Profile

RusRedmineReceivingEmails » History » Version 1

Denis Savitskiy, 2011-07-27 13:50
В процессе..

1 1 Denis Savitskiy
h1. RusRedmineReceivingEmails
2
3
{{>toc}}
4
5
Начиная с версии 0.8.0, Redmine можно настроить на создание и комментирование задач с помощью email.
6
7
h2. Настройка
8
9
You can configure Redmine to receive emails in one of the following ways:
10
11
12
Вы можете настроить Redmine для получения электронной почты одним из следующих способов:
13
14
* Пересылка электронных писем с вашего почтового сервера:
15
16
* Плюсы: работает с удаленнми почтовыми серверами, письма обрабатываются мгновенно, быстро (никакой перезагрузки окружения)
17
* Минусы: требует некоторых настроек агента передачи почты (например: Postfix, Sendmail...)
18
19
* Сбор почты с IMAP или POP3-сервера:
20
21
* Плюсы: простота установки, не нужно сконфигурировать MTA, работает с удаленного почтового сервера
22
* Минусы: письма не обрабатываются мгновенно (должны быть добавлены cron-задания, чтобы получать электронную почту регулярно)
23
24
* Чтение электронных писем из стандартного ввода:
25
26
* Плюсы: удобно для тестирования
27
* Минусы: медленный (перезагрузки окружения каждый раз, когда письмо открывается), нуждается в некоторой конфигурации вашего MTA
28
29
h3. Отправление писем с сервера
30
31
Отдельный скрипт можно использовать для переадресации входящих электронных писем с вашего почтового сервера.
32
Этот скрипт читает необработанные письма со стандартного ввода и направляет их в Redmine через HTTP-запрос.
33
Он находится в вашем redmine каталоге: @extra/mail_handler/rdm-mailhandler.rb@.
34
35
Чтобы использовать его, вам нужно включить API для получение сообщений электронной почты:
36
Зайдите _Настройки_ -> _Приём сообщений_, поставьте флажок на *Включить веб-сервис для входящих сообщений* и введите (или сгенерируйте) API ключ.
37
38
Скопируйте @rdm-mailhandler.rb@ на ваш почтовый сервер и убедитесь, что он исполненяемый, затем настройте ваш MTA.
39
40
Использование:
41
42
<pre>
43
rdm-mailhandler [options] --url=<Redmine URL> --key=<API ключ>
44
45
Обязательные:
46
  -u, --url                      URL сервера Redmine
47
  -k, --key                      Redmine API ключ
48
  
49
Общие:
50
  -h, --help                     помощь
51
  -v, --verbose                  экстра информация
52
  -V, --version                  информация о версии
53
54
Опции управления атрибутами задачи:
55
  -p, --project=PROJECT          идентификатор проекта
56
  -t, --tracker=TRACKER          трекер задачи
57
      --category=CATEGORY        категория задачи
58
      --priority=PRIORITY        приоритет задачи
59
  -o, --allow-override=ATTRS     разрешить содержимому письма переопределять
60
                                 атрибуты, определённые ранее,
61
                                 ATTRS - список атрибутов, разделённых запятой
62
</pre>
63
64
Примеры:
65
66
<pre>
67
  # Нет определённого проекта. Письма ДОЛЖНЫ содержать ключ 'Project':
68
  rdm-mailhandler --url http://redmine.domain.foo --key secret
69
  
70
  # Проект и стандартный трекер определены, но письма могут переопределять 
71
  # оба атрибута:
72
  rdm-mailhandler --url https://domain.foo/redmine --key secret \\
73
                  --project foo \\
74
                  --tracker bug \\
75
                  --allow-override tracker,priority
76
</pre>
77
78
Here is an example for a Postfix local alias (which is usually specified in @/etc/aliases@):
79
80
<pre>
81
foo: "|/path/to/rdm-mailhandler.rb --url http://redmine.domain --key secret --project foo"
82
</pre>
83
84
If your domain is setup as a virtual mailbox map (so that you use /etc/postfix/virtual_mailbox_maps to do mappings in the form @ user@example.com /path/example.com/user@) you should:
85
86
* create a mapping in @/etc/virtual@ like: @ foo@example.org foo@
87
* modify @/etc/postfix/main.cf@ to specify a transport file: @transport_maps = hash:/etc/postfix/transport@
88
* within the transport file add a line like: @ foo@example.org local:@
89
90
*Explanation:* - When you define virtual_mailbox_maps for a domain the default transport is virtual, which means specifying a local alias in @/etc/postfix/virtual@ will fail (with "unknown user"). To fix this, we override the default transport by specifying a local transport for the email address in question, which means the local alias will resolve correctly, and your script will be executed.
91
92
A front-end to rdm-mailhandler.rb has been written to allow specifying projects trough sub-addresses (name+project@example.com). See [[MailhandlerSubAddress]]
93
94
h3. Fetching emails from an IMAP server
95
96
A rake task (@redmine:email:receive_imap@) can be used to fetch incoming emails from an IMAP server. When you run the rake command from a cron job you can include the switch @-f /path/to/redmine/appdir/Rakefile@ on the rake command, because otherwise the rakefile is not found. This is an example line for a cron file that fetches mails every 30 minutes:
97
98
<code>
99
*/30 * * * * redmineuser rake -f /path/to/redmine/appdir/Rakefile redmine:email:receive_imap RAILS_ENV="production" host=imap.foo.bar username=redmine@somenet.foo password=xxx 
100
</code>
101
102
If your setup is working, but you receive mails from the cron daemon, you can suppress the output from the rake command by adding the --silent switch. That should stop cron sending mails on every execution of the command.
103
104
<code>
105
*/30 * * * * redmineuser rake -f /path/to/redmine/appdir/Rakefile --silent redmine:email:receive_imap RAILS_ENV="production" host=imap.foo.bar username=redmine@somenet.foo password=xxx 
106
</code>
107
108
The command has to go on a single line in your cronfile. Also see the other examples below, which only show the rake commands without the @-f@ option and without the cron part. 
109
110
For Windows as server "pycron":http://www.kalab.com/freeware/pycron/pycron.htm can be used to schedule a fetch task.
111
112
It can be necessary that you open the firewall on the machine for outgoing TCP connections to IMAP port 143.
113
114
Available IMAP options:
115
<pre>
116
  host=HOST                IMAP server host (default: 127.0.0.1)
117
  port=PORT                IMAP server port (default: 143)
118
  ssl=SSL                  Use SSL? (default: false)
119
  username=USERNAME        IMAP account
120
  password=PASSWORD        IMAP password
121
  folder=FOLDER            IMAP folder to read (default: INBOX)
122
  move_on_success=MAILBOX  move emails that were successfully received
123
                           to MAILBOX instead of deleting them
124
  move_on_failure=MAILBOX  move emails that were ignored to MAILBOX
125
</pre>
126
127
Issue attributes control options:
128
<pre>
129
  project=PROJECT          identifier of the target project
130
  tracker=TRACKER          name of the target tracker
131
  category=CATEGORY        name of the target category
132
  priority=PRIORITY        name of the target priority
133
  allow_override=ATTRS     allow email content to override attributes
134
                           specified by previous options
135
                           ATTRS is a comma separated list of attributes
136
</pre>
137
138
Примеры для rake команды:
139
140
<pre>
141
  # No project specified. Emails MUST contain the 'Project' keyword:
142
  
143
  rake redmine:email:receive_imap RAILS_ENV="production" \\
144
    host=imap.foo.bar username=redmine@somenet.foo password=xxx
145
146
147
  # Fixed project and default tracker specified, but emails can override
148
  # both tracker and priority attributes:
149
  
150
  rake redmine:email:receive_imap RAILS_ENV="production" \\
151
    host=imap.foo.bar username=redmine@somenet.foo password=xxx ssl=1 \\
152
    project=foo \\
153
    tracker=bug \\
154
    allow_override=tracker,priority
155
156
  # Move successful emails to the 'read' mailbox and failed emails to
157
  # the 'failed' mailbox
158
  
159
  rake redmine:email:receive_imap RAILS_ENV="production" \\
160
    host=imap.foo.bar username=redmine@somenet.foo password=xxx \\
161
    move_on_success=read move_on_failure=failed
162
163
</pre>
164
165
166
Ignored emails are marked as 'Seen' but are not deleted from the IMAP server--these include unknown user, unknown project and emails from the redmine emission account.
167
168
The option _allow_override_ is not only for overriding default values given to rake, but for every attribute in a mail. If you want to override the tracker in your mail you have to add _allow_override=tracker_ as parameter.
169
170
h3. Fetching emails from a POP3 server
171
172
_Only available in trunk and future 1.0._
173
174
A rake task (@redmine:email:receive_pop3@) can be used to fetch incoming emails from a POP3 server.
175
176
Доступные опции POP3:
177
<pre>
178
  host=HOST                POP3 server host (default: 127.0.0.1)
179
  port=PORT                POP3 server port (default: 110)
180
  username=USERNAME        POP3 account
181
  password=PASSWORD        POP3 password
182
  apop=1                   use APOP authentication (default: false)
183
  delete_unprocessed=1     delete messages that could not be processed
184
                           successfully from the server (default
185
                           behaviour is to leave them on the server)
186
</pre>
187
188
See the IMAP rake task above for issue attributes control options.
189
190
h3. Чтение писем со стандартного ввода
191
192
A rake task (@redmine:email:receive@) can be used to read a single raw email from the standard input.
193
194
<pre>
195
Issue attributes control options:
196
  project=PROJECT          identifier of the target project
197
  tracker=TRACKER          name of the target tracker
198
  category=CATEGORY        name of the target category
199
  priority=PRIORITY        name of the target priority
200
  allow_override=ATTRS     allow email content to override attributes
201
                           specified by previous options
202
                           ATTRS is a comma separated list of attributes
203
</pre>
204
205
Примеры:
206
207
<pre>
208
  # No project specified. Emails MUST contain the 'Project' keyword:
209
  rake redmine:email:read RAILS_ENV="production" < raw_email
210
211
  # Fixed project and default tracker specified, but emails can override
212
  # both tracker and priority attributes:
213
  rake redmine:email:read RAILS_ENV="production" \\
214
                  project=foo \\
215
                  tracker=bug \\
216
                  allow_override=tracker,priority < raw_email
217
</pre>
218
219
The option _allow_override_ is not only for overriding default values given to rake, but for every attribute in a mail. If you want to override the tracker in your mail you have to add _allow_override=tracker_ as parameter.
220
221
h3. Разрешение анонимным пользоваателям создавать задачи с помощью email
222
223
In order to enable this option, extra parameters have to be included.
224
225
<pre>
226
unknown_user=ACTION     how to handle emails from an unknown user ACTION can be one of the following values:
227
                        ignore: email is ignored (default)
228
                        accept: accept as anonymous user
229
                        create: create a user account
230
231
no_permission_check=1   disable permission checking when receiving the email
232
</pre>
233
234
Since version 0.9 project doesn't have to be public, but authentication required in Administration-> Settings->Authentication tab has to be unchecked.
235
236
h2. Как это работает
237
238
When receiving an email, Redmine uses the From address of the email to find the corresponding user. Emails received from unknown or locked users are ignored.
239
240
If the email subject contains something like "Re: *[xxxxxxx !#123]*", the email is processed as a reply and a note is added to issue !#123. Otherwise, a new issue is created.
241
242
h3. Target project
243
244
The target project can be specified using the @project@ option when receiving emails.  This should be the identifier of the project and *not* the name.  You can easily find the identifier in the url.
245
246
If you don't use this option, users have to specify in the email body which project the issue should be added to. This can be done by inserting a line in the email body like this: @"Project: foo"@.
247
248
Пример (тело письма):
249
250
<pre>
251
This is a new issue that will be added to project foo.
252
Here we have the issue description
253
[...]
254
255
Project: foo
256
</pre>
257
258
You can set a default project using the @project@ option and let users override this default project by using the @allow-override@ option when receiving emails.
259
Example:
260
261
<pre>
262
  # Create issues on project foo by default
263
  rake redmine:email:receive_imap [...] project=foo allow_override=project
264
</pre>
265
266
Of course, user permissions are checked and this email would be ignored if the user who sent this email is not allowed to add issues to project foo.
267
Make sure that the target project doesn't use *required* custom fields with no default value for its issues, otherwise the creation of the issue will fail.
268
269
h3. Параметры задачи
270
271
Based on the options you use when receiving emails (see @allow-override@ option), users may be able to override some attributes when submitting an issue.
272
This can be done by using the following keywords in the email body (just like @Project@): @Tracker@, @Category@, @Priority@, @Status@.
273
274
Пример (тело письма):
275
276
<pre>
277
This is a new issue that overrides a few attributes
278
[...]
279
280
Project: foo
281
Tracker: Bug
282
Priority: Urgent
283
Status: Resolved
284
</pre>
285
286
h3. Наблюдатели
287
288
If the user who sends the email has the 'Add issue watchers' permission, users that are in To or Cc field of the email are automatically added as watchers of the created issue.
289
290
h3. Формат письма и вложения
291
292
Redmine tries to use the plain text part of the email to fill the description of the issue.
293
If a HTML-only email is received, HTML tags are removed from its body.
294
295
Email attachments are automatically attached to the issue, unless their size exceeds the [[RedmineSettings#Attachment-max-size|maximum attachment size]] defined in the application settings.