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 @ 1361:7c0909052511

History | View | Annotate | Download (19.8 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2012  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
class Mailer < ActionMailer::Base
19
  layout 'mailer'
20
  helper :application
21
  helper :issues
22
  helper :custom_fields
23

    
24
  include Redmine::I18n
25

    
26
  def self.default_url_options
27
    { :host => Setting.host_name, :protocol => Setting.protocol }
28
  end
29

    
30
  # Builds a Mail::Message object used to email the specified member
31
  # that he was added to a project
32
  #
33
  # Example:
34
  #   member_added_to_project(member, project) => Mail::Message object
35
  #   Mailer.member_added_to_project(member, project) => sends an email to the registered member
36
  def member_added_to_project(member, project)
37

    
38
    principal = Principal.find(member.user_id)
39

    
40
    users = []
41
    if principal.type == "User"
42
      users = [User.find(member.user_id)]
43
    else
44
      users = Principal.find(member.user_id).users      
45
    end
46

    
47
    users.map do |user|
48

    
49
      set_language_if_valid user.language
50
      @project_url = url_for(:controller => 'projects', :action => 'show', :id => project.id)
51
      @project_name = project.name
52
      mail :to => user.mail,
53
        :subject => l(:mail_subject_added_to_project, Setting.app_title)
54

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

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

    
107
  def reminder(user, issues, days)
108
    set_language_if_valid user.language
109
    @issues = issues
110
    @days = days
111
    @issues_url = url_for(:controller => 'issues', :action => 'index',
112
                                :set_filter => 1, :assigned_to_id => user.id,
113
                                :sort => 'due_date:asc')
114
    mail :to => user.mail,
115
      :subject => l(:mail_subject_reminder, :count => issues.size, :days => days)
116
  end
117

    
118
  # Builds a Mail::Message object used to email users belonging to the added document's project.
119
  #
120
  # Example:
121
  #   document_added(document) => Mail::Message object
122
  #   Mailer.document_added(document).deliver => sends an email to the document's project recipients
123
  def document_added(document)
124
    redmine_headers 'Project' => document.project.identifier
125
    @author = User.current
126
    @document = document
127
    @document_url = url_for(:controller => 'documents', :action => 'show', :id => document)
128
    mail :to => document.recipients,
129
      :subject => "[#{document.project.name}] #{l(:label_document_new)}: #{document.title}"
130
  end
131

    
132
  # Builds a Mail::Message object used to email recipients of a project when an attachements are added.
133
  #
134
  # Example:
135
  #   attachments_added(attachments) => Mail::Message object
136
  #   Mailer.attachments_added(attachments).deliver => sends an email to the project's recipients
137
  def attachments_added(attachments)
138
    container = attachments.first.container
139
    added_to = ''
140
    added_to_url = ''
141
    @author = attachments.first.author
142
    case container.class.name
143
    when 'Project'
144
      added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container)
145
      added_to = "#{l(:label_project)}: #{container}"
146
      recipients = container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}.collect  {|u| u.mail}
147
    when 'Version'
148
      added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container.project)
149
      added_to = "#{l(:label_version)}: #{container.name}"
150
      recipients = container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}.collect  {|u| u.mail}
151
    when 'Document'
152
      added_to_url = url_for(:controller => 'documents', :action => 'show', :id => container.id)
153
      added_to = "#{l(:label_document)}: #{container.title}"
154
      recipients = container.recipients
155
    end
156
    redmine_headers 'Project' => container.project.identifier
157
    @attachments = attachments
158
    @added_to = added_to
159
    @added_to_url = added_to_url
160
    mail :to => recipients,
161
      :subject => "[#{container.project.name}] #{l(:label_attachment_new)}"
162
  end
163

    
164
  # Builds a Mail::Message object used to email recipients of a news' project when a news item is added.
165
  #
166
  # Example:
167
  #   news_added(news) => Mail::Message object
168
  #   Mailer.news_added(news).deliver => sends an email to the news' project recipients
169
  def news_added(news)
170
    redmine_headers 'Project' => news.project.identifier
171
    @author = news.author
172
    message_id news
173
    @news = news
174
    @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
175
    mail :to => news.recipients,
176
      :subject => "[#{news.project.name}] #{l(:label_news)}: #{news.title}"
177
  end
178

    
179
  # Builds a Mail::Message object used to email recipients of a news' project when a news comment is added.
180
  #
181
  # Example:
182
  #   news_comment_added(comment) => Mail::Message object
183
  #   Mailer.news_comment_added(comment) => sends an email to the news' project recipients
184
  def news_comment_added(comment)
185
    news = comment.commented
186
    redmine_headers 'Project' => news.project.identifier
187
    @author = comment.author
188
    message_id comment
189
    @news = news
190
    @comment = comment
191
    @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
192
    mail :to => news.recipients,
193
     :cc => news.watcher_recipients,
194
     :subject => "Re: [#{news.project.name}] #{l(:label_news)}: #{news.title}"
195
  end
196

    
197
  # Builds a Mail::Message object used to email the recipients of the specified message that was posted.
198
  #
199
  # Example:
200
  #   message_posted(message) => Mail::Message object
201
  #   Mailer.message_posted(message).deliver => sends an email to the recipients
202
  def message_posted(message)
203
    redmine_headers 'Project' => message.project.identifier,
204
                    'Topic-Id' => (message.parent_id || message.id)
205
    @author = message.author
206
    message_id message
207
    references message.parent unless message.parent.nil?
208
    recipients = message.recipients
209
    cc = ((message.root.watcher_recipients + message.board.watcher_recipients).uniq - recipients)
210
    @message = message
211
    @message_url = url_for(message.event_url)
212
    mail :to => recipients,
213
      :cc => cc,
214
      :subject => "[#{message.board.project.name} - #{message.board.name} - msg#{message.root.id}] #{message.subject}"
215
  end
216

    
217
  # Builds a Mail::Message object used to email the recipients of a project of the specified wiki content was added.
218
  #
219
  # Example:
220
  #   wiki_content_added(wiki_content) => Mail::Message object
221
  #   Mailer.wiki_content_added(wiki_content).deliver => sends an email to the project's recipients
222
  def wiki_content_added(wiki_content)
223
    redmine_headers 'Project' => wiki_content.project.identifier,
224
                    'Wiki-Page-Id' => wiki_content.page.id
225
    @author = wiki_content.author
226
    message_id wiki_content
227
    recipients = wiki_content.recipients
228
    cc = wiki_content.page.wiki.watcher_recipients - recipients
229
    @wiki_content = wiki_content
230
    @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
231
                                      :project_id => wiki_content.project,
232
                                      :id => wiki_content.page.title)
233
    mail :to => recipients,
234
      :cc => cc,
235
      :subject => "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_added, :id => wiki_content.page.pretty_title)}"
236
  end
237

    
238
  # Builds a Mail::Message object used to email the recipients of a project of the specified wiki content was updated.
239
  #
240
  # Example:
241
  #   wiki_content_updated(wiki_content) => Mail::Message object
242
  #   Mailer.wiki_content_updated(wiki_content).deliver => sends an email to the project's recipients
243
  def wiki_content_updated(wiki_content)
244
    redmine_headers 'Project' => wiki_content.project.identifier,
245
                    'Wiki-Page-Id' => wiki_content.page.id
246
    @author = wiki_content.author
247
    message_id wiki_content
248
    recipients = wiki_content.recipients
249
    cc = wiki_content.page.wiki.watcher_recipients + wiki_content.page.watcher_recipients - recipients
250
    @wiki_content = wiki_content
251
    @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
252
                                      :project_id => wiki_content.project,
253
                                      :id => wiki_content.page.title)
254
    @wiki_diff_url = url_for(:controller => 'wiki', :action => 'diff',
255
                                   :project_id => wiki_content.project, :id => wiki_content.page.title,
256
                                   :version => wiki_content.version)
257
    mail :to => recipients,
258
      :cc => cc,
259
      :subject => "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_updated, :id => wiki_content.page.pretty_title)}"
260
  end
261

    
262
  # Builds a Mail::Message object used to email the specified user their account information.
263
  #
264
  # Example:
265
  #   account_information(user, password) => Mail::Message object
266
  #   Mailer.account_information(user, password).deliver => sends account information to the user
267
  def account_information(user, password)
268
    set_language_if_valid user.language
269
    @user = user
270
    @password = password
271
    @login_url = url_for(:controller => 'account', :action => 'login')
272
    mail :to => user.mail,
273
      :subject => l(:mail_subject_register, Setting.app_title)
274
  end
275

    
276
  # Builds a Mail::Message object used to email all active administrators of an account activation request.
277
  #
278
  # Example:
279
  #   account_activation_request(user) => Mail::Message object
280
  #   Mailer.account_activation_request(user).deliver => sends an email to all active administrators
281
  def account_activation_request(user)
282
    # Send the email to all active administrators
283
    recipients = User.active.find(:all, :conditions => {:admin => true}).collect { |u| u.mail }.compact
284
    @user = user
285
    @url = url_for(:controller => 'users', :action => 'index',
286
                         :status => User::STATUS_REGISTERED,
287
                         :sort_key => 'created_on', :sort_order => 'desc')
288
    mail :to => recipients,
289
      :subject => l(:mail_subject_account_activation_request, Setting.app_title)
290
  end
291

    
292
  # Builds a Mail::Message object used to email the specified user that their account was activated by an administrator.
293
  #
294
  # Example:
295
  #   account_activated(user) => Mail::Message object
296
  #   Mailer.account_activated(user).deliver => sends an email to the registered user
297
  def account_activated(user)
298
    set_language_if_valid user.language
299
    @user = user
300
    @login_url = url_for(:controller => 'account', :action => 'login')
301
    mail :to => user.mail,
302
      :subject => l(:mail_subject_register, Setting.app_title)
303
  end
304

    
305
  def lost_password(token)
306
    set_language_if_valid(token.user.language)
307
    @token = token
308
    @url = url_for(:controller => 'account', :action => 'lost_password', :token => token.value)
309
    mail :to => token.user.mail,
310
      :subject => l(:mail_subject_lost_password, Setting.app_title)
311
  end
312

    
313
  def register(token)
314
    set_language_if_valid(token.user.language)
315
    @token = token
316
    @url = url_for(:controller => 'account', :action => 'activate', :token => token.value)
317
    mail :to => token.user.mail,
318
      :subject => l(:mail_subject_register, Setting.app_title)
319
  end
320

    
321
  def test_email(user)
322
    set_language_if_valid(user.language)
323
    @url = url_for(:controller => 'welcome')
324
    mail :to => user.mail,
325
      :subject => 'Redmine test'
326
  end
327

    
328
  # Overrides default deliver! method to prevent from sending an email
329
  # with no recipient, cc or bcc
330
  def deliver!(mail = @mail)
331
    set_language_if_valid @initial_language
332
    return false if (recipients.nil? || recipients.empty?) &&
333
                    (cc.nil? || cc.empty?) &&
334
                    (bcc.nil? || bcc.empty?)
335

    
336

    
337
    # Log errors when raise_delivery_errors is set to false, Rails does not
338
    raise_errors = self.class.raise_delivery_errors
339
    self.class.raise_delivery_errors = true
340
    begin
341
      return super(mail)
342
    rescue Exception => e
343
      if raise_errors
344
        raise e
345
      elsif mylogger
346
        mylogger.error "The following error occured while sending email notification: \"#{e.message}\". Check your configuration in config/configuration.yml."
347
      end
348
    ensure
349
      self.class.raise_delivery_errors = raise_errors
350
    end
351
  end
352

    
353
  # Sends reminders to issue assignees
354
  # Available options:
355
  # * :days     => how many days in the future to remind about (defaults to 7)
356
  # * :tracker  => id of tracker for filtering issues (defaults to all trackers)
357
  # * :project  => id or identifier of project to process (defaults to all projects)
358
  # * :users    => array of user/group ids who should be reminded
359
  def self.reminders(options={})
360
    days = options[:days] || 7
361
    project = options[:project] ? Project.find(options[:project]) : nil
362
    tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
363
    user_ids = options[:users]
364

    
365
    scope = Issue.open.where("#{Issue.table_name}.assigned_to_id IS NOT NULL" +
366
      " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" +
367
      " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date
368
    )
369
    scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?
370
    scope = scope.where(:project_id => project.id) if project
371
    scope = scope.where(:tracker_id => tracker.id) if tracker
372

    
373
    issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).all.group_by(&:assigned_to)
374
    issues_by_assignee.keys.each do |assignee|
375
      if assignee.is_a?(Group)
376
        assignee.users.each do |user|
377
          issues_by_assignee[user] ||= []
378
          issues_by_assignee[user] += issues_by_assignee[assignee]
379
        end
380
      end
381
    end
382

    
383
    issues_by_assignee.each do |assignee, issues|
384
      reminder(assignee, issues, days).deliver if assignee.is_a?(User) && assignee.active?
385
    end
386
  end
387

    
388
  # Activates/desactivates email deliveries during +block+
389
  def self.with_deliveries(enabled = true, &block)
390
    was_enabled = ActionMailer::Base.perform_deliveries
391
    ActionMailer::Base.perform_deliveries = !!enabled
392
    yield
393
  ensure
394
    ActionMailer::Base.perform_deliveries = was_enabled
395
  end
396

    
397
  # Sends emails synchronously in the given block
398
  def self.with_synched_deliveries(&block)
399
    saved_method = ActionMailer::Base.delivery_method
400
    if m = saved_method.to_s.match(%r{^async_(.+)$})
401
      synched_method = m[1]
402
      ActionMailer::Base.delivery_method = synched_method.to_sym
403
      ActionMailer::Base.send "#{synched_method}_settings=", ActionMailer::Base.send("async_#{synched_method}_settings")
404
    end
405
    yield
406
  ensure
407
    ActionMailer::Base.delivery_method = saved_method
408
  end
409

    
410
  def mail(headers={})
411
    headers.merge! 'X-Mailer' => 'Redmine',
412
            'X-Redmine-Host' => Setting.host_name,
413
            'X-Redmine-Site' => Setting.app_title,
414
            'X-Auto-Response-Suppress' => 'OOF',
415
            'Auto-Submitted' => 'auto-generated',
416
            'From' => Setting.mail_from,
417
            'List-Id' => "<#{Setting.mail_from.to_s.gsub('@', '.')}>"
418

    
419
    # Removes the author from the recipients and cc
420
    # if he doesn't want to receive notifications about what he does
421
    if @author && @author.logged? && @author.pref[:no_self_notified]
422
      headers[:to].delete(@author.mail) if headers[:to].is_a?(Array)
423
      headers[:cc].delete(@author.mail) if headers[:cc].is_a?(Array)
424
    end
425

    
426
    if @author && @author.logged?
427
      redmine_headers 'Sender' => @author.login
428
    end
429

    
430
    # Blind carbon copy recipients
431
    if Setting.bcc_recipients?
432
      headers[:bcc] = [headers[:to], headers[:cc]].flatten.uniq.reject(&:blank?)
433
      headers[:to] = nil
434
      headers[:cc] = nil
435
    end
436

    
437
    if @message_id_object
438
      headers[:message_id] = "<#{self.class.message_id_for(@message_id_object)}>"
439
    end
440
    if @references_objects
441
      headers[:references] = @references_objects.collect {|o| "<#{self.class.message_id_for(o)}>"}.join(' ')
442
    end
443

    
444
    super headers do |format|
445
      format.text
446
      format.html unless Setting.plain_text_mail?
447
    end
448

    
449
    set_language_if_valid @initial_language
450
  end
451

    
452
  def initialize(*args)
453
    @initial_language = current_language
454
    set_language_if_valid Setting.default_language
455
    super
456
  end
457
  
458
  def self.deliver_mail(mail)
459
    return false if mail.to.blank? && mail.cc.blank? && mail.bcc.blank?
460
    super
461
  end
462

    
463
  def self.method_missing(method, *args, &block)
464
    if m = method.to_s.match(%r{^deliver_(.+)$})
465
      ActiveSupport::Deprecation.warn "Mailer.deliver_#{m[1]}(*args) is deprecated. Use Mailer.#{m[1]}(*args).deliver instead."
466
      send(m[1], *args).deliver
467
    else
468
      super
469
    end
470
  end
471

    
472
  private
473

    
474
  # Appends a Redmine header field (name is prepended with 'X-Redmine-')
475
  def redmine_headers(h)
476
    h.each { |k,v| headers["X-Redmine-#{k}"] = v.to_s }
477
  end
478

    
479
  # Returns a predictable Message-Id for the given object
480
  def self.message_id_for(object)
481
    # id + timestamp should reduce the odds of a collision
482
    # as far as we don't send multiple emails for the same object
483
    timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on)
484
    hash = "redmine.#{object.class.name.demodulize.underscore}-#{object.id}.#{timestamp.strftime("%Y%m%d%H%M%S")}"
485
    host = Setting.mail_from.to_s.gsub(%r{^.*@}, '')
486
    host = "#{::Socket.gethostname}.redmine" if host.empty?
487
    "#{hash}@#{host}"
488
  end
489

    
490
  def message_id(object)
491
    @message_id_object = object
492
  end
493

    
494
  def references(object)
495
    @references_objects ||= []
496
    @references_objects << object
497
  end
498

    
499
  def mylogger
500
    Rails.logger
501
  end
502
end
503

    
504
# Patch TMail so that message_id is not overwritten
505

    
506
### NB: Redmine 2.2 no longer uses TMail I think? This function has
507
### been removed there
508

    
509
module TMail
510
  class Mail
511
    def add_message_id( fqdn = nil )
512
      self.message_id ||= ::TMail::new_message_id(fqdn)
513
    end
514
  end
515
end
516