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 27KB

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