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

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