To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / mailer.rb @ 438:34214e593c67

History | View | Annotate | Download (18.7 KB)

1
# redMine - project management software
2
# Copyright (C) 2006-2007  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

    
18
require 'ar_condition'
19

    
20
class Mailer < ActionMailer::Base
21
  layout 'mailer'
22
  helper :application
23
  helper :issues
24
  helper :custom_fields
25

    
26
  include ActionController::UrlWriter
27
  include Redmine::I18n
28

    
29
  def self.default_url_options
30
    h = Setting.host_name
31
    h = h.to_s.gsub(%r{\/.*$}, '') unless Redmine::Utils.relative_url_root.blank?
32
    { :host => h, :protocol => Setting.protocol }
33
  end
34

    
35

    
36

    
37
  # Builds a tmail object used to email the specified user that he was added to a project
38
  #
39
  # Example:
40
  #   add_to_project(user) => tmail object
41
  #   Mailer.deliver_add_to_project(user) => sends an email to the registered user
42
  def added_to_project(member, project)
43

    
44
    user = User.find(member.user_id)
45

    
46
    set_language_if_valid user.language
47
    recipients user.mail
48
    subject l(:mail_subject_added_to_project, Setting.app_title)
49
    body :project_url => url_for(:controller => 'projects', :action => 'show', :id => project.id),
50
        :project_name => project.name
51
    render_multipart('added_to_project', body)
52
  end
53

    
54

    
55
  
56
  # Builds a tmail object used to email recipients of the added issue.
57
  #
58
  # Example:
59
  #   issue_add(issue) => tmail object
60
  #   Mailer.deliver_issue_add(issue) => sends an email to issue recipients
61
  def issue_add(issue)
62
    redmine_headers 'Project' => issue.project.identifier,
63
                    'Issue-Id' => issue.id,
64
                    'Issue-Author' => issue.author.login
65
    redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
66
    message_id issue
67
    recipients issue.recipients
68
    cc(issue.watcher_recipients - @recipients)
69
    subject "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] (#{issue.status.name}) #{issue.subject}"
70
    body :issue => issue,
71
         :issue_url => url_for(:controller => 'issues', :action => 'show', :id => issue)
72
    render_multipart('issue_add', body)
73
  end
74

    
75
  # Builds a tmail object used to email recipients of the edited issue.
76
  #
77
  # Example:
78
  #   issue_edit(journal) => tmail object
79
  #   Mailer.deliver_issue_edit(journal) => sends an email to issue recipients
80
  def issue_edit(journal)
81
    issue = journal.journalized.reload
82
    redmine_headers 'Project' => issue.project.identifier,
83
                    'Issue-Id' => issue.id,
84
                    'Issue-Author' => issue.author.login
85
    redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
86
    message_id journal
87
    references issue
88
    @author = journal.user
89
    recipients issue.recipients
90
    # Watchers in cc
91
    cc(issue.watcher_recipients - @recipients)
92
    s = "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] "
93
    s << "(#{issue.status.name}) " if journal.new_value_for('status_id')
94
    s << issue.subject
95
    subject s
96
    body :issue => issue,
97
         :journal => journal,
98
         :issue_url => url_for(:controller => 'issues', :action => 'show', :id => issue)
99

    
100
    render_multipart('issue_edit', body)
101
  end
102

    
103
  def reminder(user, issues, days)
104
    set_language_if_valid user.language
105
    recipients user.mail
106
    subject l(:mail_subject_reminder, :count => issues.size, :days => days)
107
    body :issues => issues,
108
         :days => days,
109
         :issues_url => url_for(:controller => 'issues', :action => 'index', :set_filter => 1, :assigned_to_id => user.id, :sort_key => 'due_date', :sort_order => 'asc')
110
    render_multipart('reminder', body)
111
  end
112

    
113
  # Builds a tmail object used to email users belonging to the added document's project.
114
  #
115
  # Example:
116
  #   document_added(document) => tmail object
117
  #   Mailer.deliver_document_added(document) => sends an email to the document's project recipients
118
  def document_added(document)
119
    redmine_headers 'Project' => document.project.identifier
120
    recipients document.recipients
121
    subject "[#{document.project.name}] #{l(:label_document_new)}: #{document.title}"
122
    body :document => document,
123
         :document_url => url_for(:controller => 'documents', :action => 'show', :id => document)
124
    render_multipart('document_added', body)
125
  end
126

    
127
  # Builds a tmail object used to email recipients of a project when an attachements are added.
128
  #
129
  # Example:
130
  #   attachments_added(attachments) => tmail object
131
  #   Mailer.deliver_attachments_added(attachments) => sends an email to the project's recipients
132
  def attachments_added(attachments)
133
    container = attachments.first.container
134
    added_to = ''
135
    added_to_url = ''
136
    case container.class.name
137
    when 'Project'
138
      added_to_url = url_for(:controller => 'projects', :action => 'list_files', :id => container)
139
      added_to = "#{l(:label_project)}: #{container}"
140
      recipients container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}.collect  {|u| u.mail}
141
    when 'Version'
142
      added_to_url = url_for(:controller => 'projects', :action => 'list_files', :id => container.project_id)
143
      added_to = "#{l(:label_version)}: #{container.name}"
144
      recipients container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}.collect  {|u| u.mail}
145
    when 'Document'
146
      added_to_url = url_for(:controller => 'documents', :action => 'show', :id => container.id)
147
      added_to = "#{l(:label_document)}: #{container.title}"
148
      recipients container.recipients
149
    end
150
    redmine_headers 'Project' => container.project.identifier
151
    subject "[#{container.project.name}] #{l(:label_attachment_new)}"
152
    body :attachments => attachments,
153
         :added_to => added_to,
154
         :added_to_url => added_to_url
155
    render_multipart('attachments_added', body)
156
  end
157
  
158
  # Builds a tmail object used to email recipients of a news' project when a news item is added.
159
  #
160
  # Example:
161
  #   news_added(news) => tmail object
162
  #   Mailer.deliver_news_added(news) => sends an email to the news' project recipients
163
  def news_added(news)
164
    redmine_headers 'Project' => news.project.identifier
165
    message_id news
166
    recipients news.recipients
167
    subject "[#{news.project.name}] #{l(:label_news)}: #{news.title}"
168
    body :news => news,
169
         :news_url => url_for(:controller => 'news', :action => 'show', :id => news)
170
    render_multipart('news_added', body)
171
  end
172

    
173
  # Builds a tmail object used to email the recipients of the specified message that was posted. 
174
  #
175
  # Example:
176
  #   message_posted(message) => tmail object
177
  #   Mailer.deliver_message_posted(message) => sends an email to the recipients
178
  def message_posted(message)
179
    redmine_headers 'Project' => message.project.identifier,
180
                    'Topic-Id' => (message.parent_id || message.id)
181
    message_id message
182
    references message.parent unless message.parent.nil?
183
    recipients(message.recipients)
184
    cc((message.root.watcher_recipients + message.board.watcher_recipients).uniq - @recipients)
185
    subject "[#{message.board.project.name} - #{message.board.name} - msg#{message.root.id}] #{message.subject}"
186
    body :message => message,
187
         :message_url => url_for(message.event_url)
188
    render_multipart('message_posted', body)
189
  end
190
  
191
  # Builds a tmail object used to email the recipients of a project of the specified wiki content was added. 
192
  #
193
  # Example:
194
  #   wiki_content_added(wiki_content) => tmail object
195
  #   Mailer.deliver_wiki_content_added(wiki_content) => sends an email to the project's recipients
196
  def wiki_content_added(wiki_content)
197
    redmine_headers 'Project' => wiki_content.project.identifier,
198
                    'Wiki-Page-Id' => wiki_content.page.id
199
    message_id wiki_content
200
    recipients wiki_content.recipients
201
    cc(wiki_content.page.wiki.watcher_recipients - recipients)
202
    subject "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_added, :id => wiki_content.page.pretty_title)}"
203
    body :wiki_content => wiki_content,
204
         :wiki_content_url => url_for(:controller => 'wiki', :action => 'show', :project_id => wiki_content.project, :id => wiki_content.page.title)
205
    render_multipart('wiki_content_added', body)
206
  end
207
  
208
  # Builds a tmail object used to email the recipients of a project of the specified wiki content was updated. 
209
  #
210
  # Example:
211
  #   wiki_content_updated(wiki_content) => tmail object
212
  #   Mailer.deliver_wiki_content_updated(wiki_content) => sends an email to the project's recipients
213
  def wiki_content_updated(wiki_content)
214
    redmine_headers 'Project' => wiki_content.project.identifier,
215
                    'Wiki-Page-Id' => wiki_content.page.id
216
    message_id wiki_content
217
    recipients wiki_content.recipients
218
    cc(wiki_content.page.wiki.watcher_recipients + wiki_content.page.watcher_recipients - recipients)
219
    subject "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_updated, :id => wiki_content.page.pretty_title)}"
220
    body :wiki_content => wiki_content,
221
         :wiki_content_url => url_for(:controller => 'wiki', :action => 'show', :project_id => wiki_content.project, :id => wiki_content.page.title),
222
         :wiki_diff_url => url_for(:controller => 'wiki', :action => 'diff', :project_id => wiki_content.project, :id => wiki_content.page.title, :version => wiki_content.version)
223
    render_multipart('wiki_content_updated', body)
224
  end
225

    
226
  # Builds a tmail object used to email the specified user their account information.
227
  #
228
  # Example:
229
  #   account_information(user, password) => tmail object
230
  #   Mailer.deliver_account_information(user, password) => sends account information to the user
231
  def account_information(user, password)
232
    set_language_if_valid user.language
233
    recipients user.mail
234
    subject l(:mail_subject_register, Setting.app_title)
235
    body :user => user,
236
         :password => password,
237
         :login_url => url_for(:controller => 'account', :action => 'login')
238
    render_multipart('account_information', body)
239
  end
240

    
241
  # Builds a tmail object used to email all active administrators of an account activation request.
242
  #
243
  # Example:
244
  #   account_activation_request(user) => tmail object
245
  #   Mailer.deliver_account_activation_request(user)=> sends an email to all active administrators
246
  def account_activation_request(user)
247
    # Send the email to all active administrators
248
    recipients User.active.find(:all, :conditions => {:admin => true}).collect { |u| u.mail }.compact
249
    subject l(:mail_subject_account_activation_request, Setting.app_title)
250
    body :user => user,
251
         :url => url_for(:controller => 'users', :action => 'index', :status => User::STATUS_REGISTERED, :sort_key => 'created_on', :sort_order => 'desc')
252
    render_multipart('account_activation_request', body)
253
  end
254

    
255
  # Builds a tmail object used to email the specified user that their account was activated by an administrator.
256
  #
257
  # Example:
258
  #   account_activated(user) => tmail object
259
  #   Mailer.deliver_account_activated(user) => sends an email to the registered user
260
  def account_activated(user)
261
    set_language_if_valid user.language
262
    recipients user.mail
263
    subject l(:mail_subject_register, Setting.app_title)
264
    body :user => user,
265
         :login_url => url_for(:controller => 'account', :action => 'login')
266
    render_multipart('account_activated', body)
267
  end
268

    
269
  def lost_password(token)
270
    set_language_if_valid(token.user.language)
271
    recipients token.user.mail
272
    subject l(:mail_subject_lost_password, Setting.app_title)
273
    body :token => token,
274
         :url => url_for(:controller => 'account', :action => 'lost_password', :token => token.value)
275
    render_multipart('lost_password', body)
276
  end
277

    
278
  def register(token)
279
    set_language_if_valid(token.user.language)
280
    recipients token.user.mail
281
    subject l(:mail_subject_register, Setting.app_title)
282
    body :token => token,
283
         :url => url_for(:controller => 'account', :action => 'activate', :token => token.value)
284
    render_multipart('register', body)
285
  end
286

    
287
  def test(user)
288
    set_language_if_valid(user.language)
289
    recipients user.mail
290
    subject 'Redmine test'
291
    body :url => url_for(:controller => 'welcome')
292
    render_multipart('test', body)
293
  end
294

    
295
  # Overrides default deliver! method to prevent from sending an email
296
  # with no recipient, cc or bcc
297
  def deliver!(mail = @mail)
298
    set_language_if_valid @initial_language
299
    return false if (recipients.nil? || recipients.empty?) &&
300
                    (cc.nil? || cc.empty?) &&
301
                    (bcc.nil? || bcc.empty?)
302
                    
303
    # Set Message-Id and References
304
    if @message_id_object
305
      mail.message_id = self.class.message_id_for(@message_id_object)
306
    end
307
    if @references_objects
308
      mail.references = @references_objects.collect {|o| self.class.message_id_for(o)}
309
    end
310
    
311
    # Log errors when raise_delivery_errors is set to false, Rails does not
312
    raise_errors = self.class.raise_delivery_errors
313
    self.class.raise_delivery_errors = true
314
    begin
315
      return super(mail)
316
    rescue Exception => e
317
      if raise_errors
318
        raise e
319
      elsif mylogger
320
        mylogger.error "The following error occured while sending email notification: \"#{e.message}\". Check your configuration in config/email.yml."
321
      end
322
    ensure
323
      self.class.raise_delivery_errors = raise_errors
324
    end
325
  end
326

    
327
  # Sends reminders to issue assignees
328
  # Available options:
329
  # * :days     => how many days in the future to remind about (defaults to 7)
330
  # * :tracker  => id of tracker for filtering issues (defaults to all trackers)
331
  # * :project  => id or identifier of project to process (defaults to all projects)
332
  # * :users    => array of user ids who should be reminded
333
  def self.reminders(options={})
334
    days = options[:days] || 7
335
    project = options[:project] ? Project.find(options[:project]) : nil
336
    tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
337
    user_ids = options[:users]
338

    
339
    s = ARCondition.new ["#{IssueStatus.table_name}.is_closed = ? AND #{Issue.table_name}.due_date <= ?", false, days.day.from_now.to_date]
340
    s << "#{Issue.table_name}.assigned_to_id IS NOT NULL"
341
    s << ["#{Issue.table_name}.assigned_to_id IN (?)", user_ids] if user_ids.present?
342
    s << "#{Project.table_name}.status = #{Project::STATUS_ACTIVE}"
343
    s << "#{Issue.table_name}.project_id = #{project.id}" if project
344
    s << "#{Issue.table_name}.tracker_id = #{tracker.id}" if tracker
345

    
346
    issues_by_assignee = Issue.find(:all, :include => [:status, :assigned_to, :project, :tracker],
347
                                          :conditions => s.conditions
348
                                    ).group_by(&:assigned_to)
349
    issues_by_assignee.each do |assignee, issues|
350
      deliver_reminder(assignee, issues, days) unless assignee.nil?
351
    end
352
  end
353
  
354
  # Activates/desactivates email deliveries during +block+
355
  def self.with_deliveries(enabled = true, &block)
356
    was_enabled = ActionMailer::Base.perform_deliveries
357
    ActionMailer::Base.perform_deliveries = !!enabled
358
    yield
359
  ensure
360
    ActionMailer::Base.perform_deliveries = was_enabled
361
  end
362

    
363
  private
364
  def initialize_defaults(method_name)
365
    super
366
    @initial_language = current_language
367
    set_language_if_valid Setting.default_language
368
    from Setting.mail_from
369
    
370
    # Common headers
371
    headers 'X-Mailer' => 'Redmine',
372
            'X-Redmine-Host' => Setting.host_name,
373
            'X-Redmine-Site' => Setting.app_title,
374
            'Precedence' => 'bulk',
375
            'Auto-Submitted' => 'auto-generated'
376
  end
377

    
378
  # Appends a Redmine header field (name is prepended with 'X-Redmine-')
379
  def redmine_headers(h)
380
    h.each { |k,v| headers["X-Redmine-#{k}"] = v }
381
  end
382

    
383
  # Overrides the create_mail method
384
  def create_mail
385
    # Removes the current user from the recipients and cc
386
    # if he doesn't want to receive notifications about what he does
387
    @author ||= User.current
388
    if @author.pref[:no_self_notified]
389
      recipients.delete(@author.mail) if recipients
390
      cc.delete(@author.mail) if cc
391
    end
392
    
393
    notified_users = [recipients, cc].flatten.compact.uniq
394
    # Rails would log recipients only, not cc and bcc
395
    mylogger.info "Sending email notification to: #{notified_users.join(', ')}" if mylogger
396
    
397
    # Blind carbon copy recipients
398
    if Setting.bcc_recipients?
399
      bcc(notified_users)
400
      recipients []
401
      cc []
402
    end
403
    super
404
  end
405

    
406
  # Rails 2.3 has problems rendering implicit multipart messages with
407
  # layouts so this method will wrap an multipart messages with
408
  # explicit parts.
409
  #
410
  # https://rails.lighthouseapp.com/projects/8994/tickets/2338-actionmailer-mailer-views-and-content-type
411
  # https://rails.lighthouseapp.com/projects/8994/tickets/1799-actionmailer-doesnt-set-template_format-when-rendering-layouts
412
  
413
  def render_multipart(method_name, body)
414
    if Setting.plain_text_mail?
415
      content_type "text/plain"
416
      body render(:file => "#{method_name}.text.plain.rhtml", :body => body, :layout => 'mailer.text.plain.erb')
417
    else
418
      content_type "multipart/alternative"
419
      part :content_type => "text/plain", :body => render(:file => "#{method_name}.text.plain.rhtml", :body => body, :layout => 'mailer.text.plain.erb')
420
      part :content_type => "text/html", :body => render_message("#{method_name}.text.html.rhtml", body)
421
    end
422
  end
423

    
424
  # Makes partial rendering work with Rails 1.2 (retro-compatibility)
425
  def self.controller_path
426
    ''
427
  end unless respond_to?('controller_path')
428
  
429
  # Returns a predictable Message-Id for the given object
430
  def self.message_id_for(object)
431
    # id + timestamp should reduce the odds of a collision
432
    # as far as we don't send multiple emails for the same object
433
    timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on) 
434
    hash = "redmine.#{object.class.name.demodulize.underscore}-#{object.id}.#{timestamp.strftime("%Y%m%d%H%M%S")}"
435
    host = Setting.mail_from.to_s.gsub(%r{^.*@}, '')
436
    host = "#{::Socket.gethostname}.redmine" if host.empty?
437
    "<#{hash}@#{host}>"
438
  end
439
  
440
  private
441
  
442
  def message_id(object)
443
    @message_id_object = object
444
  end
445
  
446
  def references(object)
447
    @references_objects ||= []
448
    @references_objects << object
449
  end
450
    
451
  def mylogger
452
    RAILS_DEFAULT_LOGGER
453
  end
454
end
455

    
456
# Patch TMail so that message_id is not overwritten
457
module TMail
458
  class Mail
459
    def add_message_id( fqdn = nil )
460
      self.message_id ||= ::TMail::new_message_id(fqdn)
461
    end
462
  end
463
end
464

    
465

    
466

    
467