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

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