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 @ 403:b15397a5341c

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
    logger.debug "ABRACADABRA"
47
    logger.debug project.name
48

    
49

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

    
58

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

    
79
  # Builds a tmail object used to email recipients of the edited issue.
80
  #
81
  # Example:
82
  #   issue_edit(journal) => tmail object
83
  #   Mailer.deliver_issue_edit(journal) => 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 issue.recipients
94
    # Watchers in cc
95
    cc(issue.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
    subject s
100
    body :issue => issue,
101
         :journal => journal,
102
         :issue_url => url_for(:controller => 'issues', :action => 'show', :id => issue)
103

    
104
    render_multipart('issue_edit', body)
105
  end
106

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

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

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

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

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

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

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

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

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

    
291
  def test(user)
292
    set_language_if_valid(user.language)
293
    recipients user.mail
294
    subject 'Redmine test'
295
    body :url => url_for(:controller => 'welcome')
296
    render_multipart('test', body)
297
  end
298

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

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

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

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

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

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

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

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

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

    
460
# Patch TMail so that message_id is not overwritten
461
module TMail
462
  class Mail
463
    def add_message_id( fqdn = nil )
464
      self.message_id ||= ::TMail::new_message_id(fqdn)
465
    end
466
  end
467
end
468

    
469

    
470

    
471