You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mailer.rb 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2017 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. require 'roadie'
  18. class Mailer < ActionMailer::Base
  19. layout 'mailer'
  20. helper :application
  21. helper :issues
  22. helper :custom_fields
  23. include Redmine::I18n
  24. include Roadie::Rails::Automatic
  25. # Overrides ActionMailer::Base#process in order to set the recipient as the current user
  26. # and his language as the default locale.
  27. # The first argument of all actions of this Mailer must be a User (the recipient),
  28. # otherwise an ArgumentError is raised.
  29. def process(action, *args)
  30. user = args.first
  31. raise ArgumentError, "First argument has to be a user, was #{user.inspect}" unless user.is_a?(User)
  32. initial_user = User.current
  33. initial_language = ::I18n.locale
  34. begin
  35. User.current = user
  36. lang = find_language(user.language) if user.logged?
  37. lang ||= Setting.default_language
  38. set_language_if_valid(lang)
  39. super(action, *args)
  40. ensure
  41. User.current = initial_user
  42. ::I18n.locale = initial_language
  43. end
  44. end
  45. # Default URL options for generating URLs in emails based on host_name and protocol
  46. # defined in application settings.
  47. def self.default_url_options
  48. options = {:protocol => Setting.protocol}
  49. if Setting.host_name.to_s =~ /\A(https?\:\/\/)?(.+?)(\:(\d+))?(\/.+)?\z/i
  50. host, port, prefix = $2, $4, $5
  51. options.merge!({
  52. :host => host, :port => port, :script_name => prefix
  53. })
  54. else
  55. options[:host] = Setting.host_name
  56. end
  57. options
  58. end
  59. # Builds a mail for notifying user about a new issue
  60. def issue_add(user, issue)
  61. redmine_headers 'Project' => issue.project.identifier,
  62. 'Issue-Id' => issue.id,
  63. 'Issue-Author' => issue.author.login
  64. redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
  65. message_id issue
  66. references issue
  67. @author = issue.author
  68. @issue = issue
  69. @user = user
  70. @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue)
  71. mail :to => user,
  72. :subject => "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] (#{issue.status.name}) #{issue.subject}"
  73. end
  74. # Notifies users about a new issue.
  75. #
  76. # Example:
  77. # Mailer.deliver_issue_add(issue)
  78. def self.deliver_issue_add(issue)
  79. users = issue.notified_users | issue.notified_watchers
  80. users.each do |user|
  81. issue_add(user, issue).deliver_later
  82. end
  83. end
  84. # Builds a mail for notifying user about an issue update
  85. def issue_edit(user, journal)
  86. issue = journal.journalized
  87. redmine_headers 'Project' => issue.project.identifier,
  88. 'Issue-Id' => issue.id,
  89. 'Issue-Author' => issue.author.login
  90. redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
  91. message_id journal
  92. references issue
  93. @author = journal.user
  94. s = "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] "
  95. s << "(#{issue.status.name}) " if journal.new_value_for('status_id')
  96. s << issue.subject
  97. @issue = issue
  98. @user = user
  99. @journal = journal
  100. @journal_details = journal.visible_details
  101. @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue, :anchor => "change-#{journal.id}")
  102. mail :to => user,
  103. :subject => s
  104. end
  105. # Notifies users about an issue update.
  106. #
  107. # Example:
  108. # Mailer.deliver_issue_edit(journal)
  109. def self.deliver_issue_edit(journal)
  110. users = journal.notified_users | journal.notified_watchers
  111. users.select! do |user|
  112. journal.notes? || journal.visible_details(user).any?
  113. end
  114. users.each do |user|
  115. issue_edit(user, journal).deliver_later
  116. end
  117. end
  118. # Builds a mail to user about a new document.
  119. def document_added(user, document, author)
  120. redmine_headers 'Project' => document.project.identifier
  121. @author = author
  122. @document = document
  123. @document_url = url_for(:controller => 'documents', :action => 'show', :id => document)
  124. mail :to => user,
  125. :subject => "[#{document.project.name}] #{l(:label_document_new)}: #{document.title}"
  126. end
  127. # Notifies users that document was created by author
  128. #
  129. # Example:
  130. # Mailer.deliver_document_added(document, author)
  131. def self.deliver_document_added(document, author)
  132. users = document.notified_users
  133. users.each do |user|
  134. document_added(user, document, author).deliver_later
  135. end
  136. end
  137. # Builds a mail to user about new attachements.
  138. def attachments_added(user, attachments)
  139. container = attachments.first.container
  140. added_to = ''
  141. added_to_url = ''
  142. @author = attachments.first.author
  143. case container.class.name
  144. when 'Project'
  145. added_to_url = url_for(:controller => 'files', :action => 'index', :project_id => container)
  146. added_to = "#{l(:label_project)}: #{container}"
  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. when 'Document'
  151. added_to_url = url_for(:controller => 'documents', :action => 'show', :id => container.id)
  152. added_to = "#{l(:label_document)}: #{container.title}"
  153. end
  154. redmine_headers 'Project' => container.project.identifier
  155. @attachments = attachments
  156. @added_to = added_to
  157. @added_to_url = added_to_url
  158. mail :to => user,
  159. :subject => "[#{container.project.name}] #{l(:label_attachment_new)}"
  160. end
  161. # Notifies users about new attachments
  162. #
  163. # Example:
  164. # Mailer.deliver_attachments_added(attachments)
  165. def self.deliver_attachments_added(attachments)
  166. container = attachments.first.container
  167. case container.class.name
  168. when 'Project', 'Version'
  169. users = container.project.notified_users.select {|user| user.allowed_to?(:view_files, container.project)}
  170. when 'Document'
  171. users = container.notified_users
  172. end
  173. users.each do |user|
  174. attachments_added(user, attachments).deliver_later
  175. end
  176. end
  177. # Builds a mail to user about a new news.
  178. def news_added(user, news)
  179. redmine_headers 'Project' => news.project.identifier
  180. @author = news.author
  181. message_id news
  182. references news
  183. @news = news
  184. @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
  185. mail :to => user,
  186. :subject => "[#{news.project.name}] #{l(:label_news)}: #{news.title}"
  187. end
  188. # Notifies users about new news
  189. #
  190. # Example:
  191. # Mailer.deliver_news_added(news)
  192. def self.deliver_news_added(news)
  193. users = news.notified_users | news.notified_watchers_for_added_news
  194. users.each do |user|
  195. news_added(user, news).deliver_later
  196. end
  197. end
  198. # Builds a mail to user about a new news comment.
  199. def news_comment_added(user, comment)
  200. news = comment.commented
  201. redmine_headers 'Project' => news.project.identifier
  202. @author = comment.author
  203. message_id comment
  204. references news
  205. @news = news
  206. @comment = comment
  207. @news_url = url_for(:controller => 'news', :action => 'show', :id => news)
  208. mail :to => user,
  209. :subject => "Re: [#{news.project.name}] #{l(:label_news)}: #{news.title}"
  210. end
  211. # Notifies users about a new comment on a news
  212. #
  213. # Example:
  214. # Mailer.deliver_news_comment_added(comment)
  215. def self.deliver_news_comment_added(comment)
  216. news = comment.commented
  217. users = news.notified_users | news.notified_watchers
  218. users.each do |user|
  219. news_comment_added(user, comment).deliver_later
  220. end
  221. end
  222. # Builds a mail to user about a new message.
  223. def message_posted(user, message)
  224. redmine_headers 'Project' => message.project.identifier,
  225. 'Topic-Id' => (message.parent_id || message.id)
  226. @author = message.author
  227. message_id message
  228. references message.root
  229. @message = message
  230. @message_url = url_for(message.event_url)
  231. mail :to => user,
  232. :subject => "[#{message.board.project.name} - #{message.board.name} - msg#{message.root.id}] #{message.subject}"
  233. end
  234. # Notifies users about a new forum message.
  235. #
  236. # Example:
  237. # Mailer.deliver_message_posted(message)
  238. def self.deliver_message_posted(message)
  239. users = message.notified_users
  240. users |= message.root.notified_watchers
  241. users |= message.board.notified_watchers
  242. users.each do |user|
  243. message_posted(user, message).deliver_later
  244. end
  245. end
  246. # Builds a mail to user about a new wiki content.
  247. def wiki_content_added(user, wiki_content)
  248. redmine_headers 'Project' => wiki_content.project.identifier,
  249. 'Wiki-Page-Id' => wiki_content.page.id
  250. @author = wiki_content.author
  251. message_id wiki_content
  252. @wiki_content = wiki_content
  253. @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
  254. :project_id => wiki_content.project,
  255. :id => wiki_content.page.title)
  256. mail :to => user,
  257. :subject => "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_added, :id => wiki_content.page.pretty_title)}"
  258. end
  259. # Notifies users about a new wiki content (wiki page added).
  260. #
  261. # Example:
  262. # Mailer.deliver_wiki_content_added(wiki_content)
  263. def self.deliver_wiki_content_added(wiki_content)
  264. users = wiki_content.notified_users | wiki_content.page.wiki.notified_watchers
  265. users.each do |user|
  266. wiki_content_added(user, wiki_content).deliver_later
  267. end
  268. end
  269. # Builds a mail to user about an update of the specified wiki content.
  270. def wiki_content_updated(user, wiki_content)
  271. redmine_headers 'Project' => wiki_content.project.identifier,
  272. 'Wiki-Page-Id' => wiki_content.page.id
  273. @author = wiki_content.author
  274. message_id wiki_content
  275. @wiki_content = wiki_content
  276. @wiki_content_url = url_for(:controller => 'wiki', :action => 'show',
  277. :project_id => wiki_content.project,
  278. :id => wiki_content.page.title)
  279. @wiki_diff_url = url_for(:controller => 'wiki', :action => 'diff',
  280. :project_id => wiki_content.project, :id => wiki_content.page.title,
  281. :version => wiki_content.version)
  282. mail :to => user,
  283. :subject => "[#{wiki_content.project.name}] #{l(:mail_subject_wiki_content_updated, :id => wiki_content.page.pretty_title)}"
  284. end
  285. # Notifies users about the update of the specified wiki content
  286. #
  287. # Example:
  288. # Mailer.deliver_wiki_content_updated(wiki_content)
  289. def self.deliver_wiki_content_updated(wiki_content)
  290. users = wiki_content.notified_users
  291. users |= wiki_content.page.notified_watchers
  292. users |= wiki_content.page.wiki.notified_watchers
  293. users.each do |user|
  294. wiki_content_updated(user, wiki_content).deliver_later
  295. end
  296. end
  297. # Builds a mail to user about his account information.
  298. def account_information(user, password)
  299. @user = user
  300. @password = password
  301. @login_url = url_for(:controller => 'account', :action => 'login')
  302. mail :to => user.mail,
  303. :subject => l(:mail_subject_register, Setting.app_title)
  304. end
  305. # Notifies user about his account information.
  306. def self.deliver_account_information(user, password)
  307. account_information(user, password).deliver_later
  308. end
  309. # Builds a mail to user about an account activation request.
  310. def account_activation_request(user, new_user)
  311. @new_user = new_user
  312. @url = url_for(:controller => 'users', :action => 'index',
  313. :status => User::STATUS_REGISTERED,
  314. :sort_key => 'created_on', :sort_order => 'desc')
  315. mail :to => user,
  316. :subject => l(:mail_subject_account_activation_request, Setting.app_title)
  317. end
  318. # Notifies admin users that an account activation request needs
  319. # their approval.
  320. #
  321. # Exemple:
  322. # Mailer.deliver_account_activation_request(new_user)
  323. def self.deliver_account_activation_request(new_user)
  324. # Send the email to all active administrators
  325. users = User.active.where(:admin => true)
  326. users.each do |user|
  327. account_activation_request(user, new_user).deliver_later
  328. end
  329. end
  330. # Builds a mail to notify user that his account was activated.
  331. def account_activated(user)
  332. @user = user
  333. @login_url = url_for(:controller => 'account', :action => 'login')
  334. mail :to => user.mail,
  335. :subject => l(:mail_subject_register, Setting.app_title)
  336. end
  337. # Notifies user that his account was activated.
  338. #
  339. # Exemple:
  340. # Mailer.deliver_account_activated(user)
  341. def self.deliver_account_activated(user)
  342. account_activated(user).deliver_later
  343. end
  344. # Builds a mail with the password recovery link.
  345. def lost_password(user, token, recipient=nil)
  346. recipient ||= user.mail
  347. @token = token
  348. @url = url_for(:controller => 'account', :action => 'lost_password', :token => token.value)
  349. mail :to => recipient,
  350. :subject => l(:mail_subject_lost_password, Setting.app_title)
  351. end
  352. # Sends an email to user with a password recovery link.
  353. # The email will be sent to the email address specifiedby recipient if provided.
  354. #
  355. # Exemple:
  356. # Mailer.deliver_account_activated(user, token)
  357. # Mailer.deliver_account_activated(user, token, 'foo@example.net')
  358. def self.deliver_lost_password(user, token, recipient=nil)
  359. lost_password(user, token, recipient).deliver_later
  360. end
  361. # Notifies user that his password was updated by sender.
  362. #
  363. # Exemple:
  364. # Mailer.deliver_password_updated(user, sender)
  365. def self.deliver_password_updated(user, sender)
  366. # Don't send a notification to the dummy email address when changing the password
  367. # of the default admin account which is required after the first login
  368. # TODO: maybe not the best way to handle this
  369. return if user.admin? && user.login == 'admin' && user.mail == 'admin@example.net'
  370. deliver_security_notification(user,
  371. sender,
  372. message: :mail_body_password_updated,
  373. title: :button_change_password,
  374. url: {controller: 'my', action: 'password'}
  375. )
  376. end
  377. # Builds a mail to user with his account activation link.
  378. def register(user, token)
  379. @token = token
  380. @url = url_for(:controller => 'account', :action => 'activate', :token => token.value)
  381. mail :to => user.mail,
  382. :subject => l(:mail_subject_register, Setting.app_title)
  383. end
  384. # Sends an mail to user with his account activation link.
  385. #
  386. # Exemple:
  387. # Mailer.deliver_register(user, token)
  388. def self.deliver_register(user, token)
  389. register(user, token).deliver_later
  390. end
  391. # Build a mail to user and the additional recipients given in
  392. # options[:recipients] about a security related event made by sender.
  393. #
  394. # Example:
  395. # security_notification(user,
  396. # sender,
  397. # message: :mail_body_security_notification_add,
  398. # field: :field_mail,
  399. # value: address
  400. # ) => Mail::Message object
  401. def security_notification(user, sender, options={})
  402. @sender = sender
  403. redmine_headers 'Sender' => sender.login
  404. @message = l(options[:message],
  405. field: (options[:field] && l(options[:field])),
  406. value: options[:value]
  407. )
  408. @title = options[:title] && l(options[:title])
  409. @remote_ip = options[:remote_ip] || @sender.remote_ip
  410. @url = options[:url] && (options[:url].is_a?(Hash) ? url_for(options[:url]) : options[:url])
  411. redmine_headers 'Url' => @url
  412. mail :to => [user, *options[:recipients]].uniq,
  413. :subject => "[#{Setting.app_title}] #{l(:mail_subject_security_notification)}"
  414. end
  415. # Notifies the given users about a security related event made by sender.
  416. #
  417. # You can specify additional recipients in options[:recipients]. These will be
  418. # added to all generated mails for all given users. Usually, you'll want to
  419. # give only a single user when setting the additional recipients.
  420. #
  421. # Example:
  422. # Mailer.deliver_security_notification(users,
  423. # sender,
  424. # message: :mail_body_security_notification_add,
  425. # field: :field_mail,
  426. # value: address
  427. # )
  428. def self.deliver_security_notification(users, sender, options={})
  429. # Symbols cannot be serialized:
  430. # ActiveJob::SerializationError: Unsupported argument type: Symbol
  431. options = options.transform_values {|v| v.is_a?(Symbol) ? v.to_s : v }
  432. # sender's remote_ip would be lost on serialization/deserialization
  433. # we have to pass it with options
  434. options[:remote_ip] ||= sender.remote_ip
  435. Array.wrap(users).each do |user|
  436. security_notification(user, sender, options).deliver_later
  437. end
  438. end
  439. # Build a mail to user about application settings changes made by sender.
  440. def settings_updated(user, sender, changes, options={})
  441. @sender = sender
  442. redmine_headers 'Sender' => sender.login
  443. @changes = changes
  444. @remote_ip = options[:remote_ip] || @sender.remote_ip
  445. @url = url_for(controller: 'settings', action: 'index')
  446. mail :to => user,
  447. :subject => "[#{Setting.app_title}] #{l(:mail_subject_security_notification)}"
  448. end
  449. # Notifies admins about application settings changes made by sender, where
  450. # changes is an array of settings names.
  451. #
  452. # Exemple:
  453. # Mailer.deliver_settings_updated(sender, [:login_required, :self_registration])
  454. def self.deliver_settings_updated(sender, changes, options={})
  455. return unless changes.present?
  456. # Symbols cannot be serialized:
  457. # ActiveJob::SerializationError: Unsupported argument type: Symbol
  458. changes = changes.map(&:to_s)
  459. # sender's remote_ip would be lost on serialization/deserialization
  460. # we have to pass it with options
  461. options[:remote_ip] ||= sender.remote_ip
  462. users = User.active.where(admin: true).to_a
  463. users.each do |user|
  464. settings_updated(user, sender, changes, options).deliver_later
  465. end
  466. end
  467. # Build a test email to user.
  468. def test_email(user)
  469. @url = url_for(:controller => 'welcome')
  470. mail :to => user,
  471. :subject => 'Redmine test'
  472. end
  473. # Send a test email to user. Will raise error that may occur during delivery.
  474. #
  475. # Exemple:
  476. # Mailer.deliver_test_email(user)
  477. def self.deliver_test_email(user)
  478. raise_delivery_errors_was = self.raise_delivery_errors
  479. self.raise_delivery_errors = true
  480. # Email must be delivered synchronously so we can catch errors
  481. test_email(user).deliver_now
  482. ensure
  483. self.raise_delivery_errors = raise_delivery_errors_was
  484. end
  485. # Builds a reminder mail to user about issues that are due in the next days.
  486. def reminder(user, issues, days)
  487. @issues = issues
  488. @days = days
  489. @issues_url = url_for(:controller => 'issues', :action => 'index',
  490. :set_filter => 1, :assigned_to_id => user.id,
  491. :sort => 'due_date:asc')
  492. mail :to => user,
  493. :subject => l(:mail_subject_reminder, :count => issues.size, :days => days)
  494. end
  495. # Sends reminders to issue assignees
  496. # Available options:
  497. # * :days => how many days in the future to remind about (defaults to 7)
  498. # * :tracker => id of tracker for filtering issues (defaults to all trackers)
  499. # * :project => id or identifier of project to process (defaults to all projects)
  500. # * :users => array of user/group ids who should be reminded
  501. # * :version => name of target version for filtering issues (defaults to none)
  502. def self.reminders(options={})
  503. days = options[:days] || 7
  504. project = options[:project] ? Project.find(options[:project]) : nil
  505. tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
  506. target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil
  507. if options[:version] && target_version_id.blank?
  508. raise ActiveRecord::RecordNotFound.new("Couldn't find Version named #{options[:version]}")
  509. end
  510. user_ids = options[:users]
  511. scope = Issue.open.where("#{Issue.table_name}.assigned_to_id IS NOT NULL" +
  512. " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" +
  513. " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date
  514. )
  515. scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?
  516. scope = scope.where(:project_id => project.id) if project
  517. scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present?
  518. scope = scope.where(:tracker_id => tracker.id) if tracker
  519. issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).
  520. group_by(&:assigned_to)
  521. issues_by_assignee.keys.each do |assignee|
  522. if assignee.is_a?(Group)
  523. assignee.users.each do |user|
  524. issues_by_assignee[user] ||= []
  525. issues_by_assignee[user] += issues_by_assignee[assignee]
  526. end
  527. end
  528. end
  529. issues_by_assignee.each do |assignee, issues|
  530. if assignee.is_a?(User) && assignee.active? && issues.present?
  531. visible_issues = issues.select {|i| i.visible?(assignee)}
  532. visible_issues.sort!{|a, b| (a.due_date <=> b.due_date).nonzero? || (a.id <=> b.id)}
  533. reminder(assignee, visible_issues, days).deliver_later if visible_issues.present?
  534. end
  535. end
  536. end
  537. # Activates/desactivates email deliveries during +block+
  538. def self.with_deliveries(enabled = true, &block)
  539. was_enabled = ActionMailer::Base.perform_deliveries
  540. ActionMailer::Base.perform_deliveries = !!enabled
  541. yield
  542. ensure
  543. ActionMailer::Base.perform_deliveries = was_enabled
  544. end
  545. # Execute the given block with inline sending of emails if the default Async
  546. # queue is used for the mailer. See the Rails guide:
  547. # Using the asynchronous queue from a Rake task will generally not work because
  548. # Rake will likely end, causing the in-process thread pool to be deleted, before
  549. # any/all of the .deliver_later emails are processed
  550. def self.with_synched_deliveries(&block)
  551. adapter = ActionMailer::DeliveryJob.queue_adapter
  552. if adapter.is_a?(ActiveJob::QueueAdapters::AsyncAdapter)
  553. ActionMailer::DeliveryJob.queue_adapter = ActiveJob::QueueAdapters::InlineAdapter.new
  554. end
  555. yield
  556. ensure
  557. ActionMailer::DeliveryJob.queue_adapter = adapter
  558. end
  559. def mail(headers={}, &block)
  560. # Add a display name to the From field if Setting.mail_from does not
  561. # include it
  562. mail_from = Mail::Address.new(Setting.mail_from)
  563. if mail_from.display_name.blank? && mail_from.comments.blank?
  564. mail_from.display_name =
  565. (@author && @author.logged?) ? @author.name : Setting.app_title
  566. end
  567. headers.reverse_merge! 'X-Mailer' => 'Redmine',
  568. 'X-Redmine-Host' => Setting.host_name,
  569. 'X-Redmine-Site' => Setting.app_title,
  570. 'X-Auto-Response-Suppress' => 'All',
  571. 'Auto-Submitted' => 'auto-generated',
  572. 'From' => mail_from.format,
  573. 'List-Id' => "<#{mail_from.address.to_s.tr('@', '.')}>"
  574. # Replaces users with their email addresses
  575. [:to, :cc, :bcc].each do |key|
  576. if headers[key].present?
  577. headers[key] = self.class.email_addresses(headers[key])
  578. end
  579. end
  580. # Removes the author from the recipients and cc
  581. # if the author does not want to receive notifications
  582. # about what the author do
  583. if @author && @author.logged? && @author.pref.no_self_notified
  584. addresses = @author.mails
  585. headers[:to] -= addresses if headers[:to].is_a?(Array)
  586. headers[:cc] -= addresses if headers[:cc].is_a?(Array)
  587. end
  588. if @author && @author.logged?
  589. redmine_headers 'Sender' => @author.login
  590. end
  591. # Blind carbon copy recipients
  592. if Setting.bcc_recipients?
  593. headers[:bcc] = [headers[:to], headers[:cc]].flatten.uniq.reject(&:blank?)
  594. headers[:to] = nil
  595. headers[:cc] = nil
  596. end
  597. if @message_id_object
  598. headers[:message_id] = "<#{self.class.message_id_for(@message_id_object)}>"
  599. end
  600. if @references_objects
  601. headers[:references] = @references_objects.collect {|o| "<#{self.class.references_for(o)}>"}.join(' ')
  602. end
  603. if block_given?
  604. super headers, &block
  605. else
  606. super headers do |format|
  607. format.text
  608. format.html unless Setting.plain_text_mail?
  609. end
  610. end
  611. end
  612. def self.deliver_mail(mail)
  613. return false if mail.to.blank? && mail.cc.blank? && mail.bcc.blank?
  614. begin
  615. # Log errors when raise_delivery_errors is set to false, Rails does not
  616. mail.raise_delivery_errors = true
  617. super
  618. rescue Exception => e
  619. if ActionMailer::Base.raise_delivery_errors
  620. raise e
  621. else
  622. Rails.logger.error "Email delivery error: #{e.message}"
  623. end
  624. end
  625. end
  626. # Returns an array of email addresses to notify by
  627. # replacing users in arg with their notified email addresses
  628. #
  629. # Example:
  630. # Mailer.email_addresses(users)
  631. # => ["foo@example.net", "bar@example.net"]
  632. def self.email_addresses(arg)
  633. arr = Array.wrap(arg)
  634. mails = arr.reject {|a| a.is_a? Principal}
  635. users = arr - mails
  636. if users.any?
  637. mails += EmailAddress.
  638. where(:user_id => users.map(&:id)).
  639. where("is_default = ? OR notify = ?", true, true).
  640. pluck(:address)
  641. end
  642. mails
  643. end
  644. private
  645. # Appends a Redmine header field (name is prepended with 'X-Redmine-')
  646. def redmine_headers(h)
  647. h.each { |k,v| headers["X-Redmine-#{k}"] = v.to_s }
  648. end
  649. def self.token_for(object, rand=true)
  650. timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on)
  651. hash = [
  652. "redmine",
  653. "#{object.class.name.demodulize.underscore}-#{object.id}",
  654. timestamp.strftime("%Y%m%d%H%M%S")
  655. ]
  656. if rand
  657. hash << Redmine::Utils.random_hex(8)
  658. end
  659. host = Setting.mail_from.to_s.strip.gsub(%r{^.*@|>}, '')
  660. host = "#{::Socket.gethostname}.redmine" if host.empty?
  661. "#{hash.join('.')}@#{host}"
  662. end
  663. # Returns a Message-Id for the given object
  664. def self.message_id_for(object)
  665. token_for(object, true)
  666. end
  667. # Returns a uniq token for a given object referenced by all notifications
  668. # related to this object
  669. def self.references_for(object)
  670. token_for(object, false)
  671. end
  672. def message_id(object)
  673. @message_id_object = object
  674. end
  675. def references(object)
  676. @references_objects ||= []
  677. @references_objects << object
  678. end
  679. end