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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2022 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 | issue.notified_mentions
  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 | journal.notified_mentions | journal.journalized.notified_mentions
  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 | wiki_content.notified_mentions
  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 |= wiki_content.notified_mentions
  317. users.each do |user|
  318. wiki_content_updated(user, wiki_content).deliver_later
  319. end
  320. end
  321. # Builds a mail to user about his account information.
  322. def account_information(user, password)
  323. @user = user
  324. @password = password
  325. @login_url = url_for(:controller => 'account', :action => 'login')
  326. mail :to => user.mail,
  327. :subject => l(:mail_subject_register, Setting.app_title)
  328. end
  329. # Notifies user about his account information.
  330. def self.deliver_account_information(user, password)
  331. account_information(user, password).deliver_later
  332. end
  333. # Builds a mail to user about an account activation request.
  334. def account_activation_request(user, new_user)
  335. @new_user = new_user
  336. @url = url_for(:controller => 'users', :action => 'index',
  337. :status => User::STATUS_REGISTERED,
  338. :sort_key => 'created_on', :sort_order => 'desc')
  339. mail :to => user,
  340. :subject => l(:mail_subject_account_activation_request, Setting.app_title)
  341. end
  342. # Notifies admin users that an account activation request needs
  343. # their approval.
  344. #
  345. # Exemple:
  346. # Mailer.deliver_account_activation_request(new_user)
  347. def self.deliver_account_activation_request(new_user)
  348. # Send the email to all active administrators
  349. users = User.active.where(:admin => true)
  350. users.each do |user|
  351. account_activation_request(user, new_user).deliver_later
  352. end
  353. end
  354. # Builds a mail to notify user that his account was activated.
  355. def account_activated(user)
  356. @user = user
  357. @login_url = url_for(:controller => 'account', :action => 'login')
  358. mail :to => user.mail,
  359. :subject => l(:mail_subject_register, Setting.app_title)
  360. end
  361. # Notifies user that his account was activated.
  362. #
  363. # Exemple:
  364. # Mailer.deliver_account_activated(user)
  365. def self.deliver_account_activated(user)
  366. account_activated(user).deliver_later
  367. end
  368. # Builds a mail with the password recovery link.
  369. def lost_password(user, token, recipient=nil)
  370. recipient ||= user.mail
  371. @token = token
  372. @url = url_for(:controller => 'account', :action => 'lost_password', :token => token.value)
  373. mail :to => recipient,
  374. :subject => l(:mail_subject_lost_password, Setting.app_title)
  375. end
  376. # Sends an email to user with a password recovery link.
  377. # The email will be sent to the email address specifiedby recipient if provided.
  378. #
  379. # Exemple:
  380. # Mailer.deliver_lost_password(user, token)
  381. # Mailer.deliver_lost_password(user, token, 'foo@example.net')
  382. def self.deliver_lost_password(user, token, recipient=nil)
  383. lost_password(user, token, recipient).deliver_later
  384. end
  385. # Notifies user that his password was updated by sender.
  386. #
  387. # Exemple:
  388. # Mailer.deliver_password_updated(user, sender)
  389. def self.deliver_password_updated(user, sender)
  390. # Don't send a notification to the dummy email address when changing the password
  391. # of the default admin account which is required after the first login
  392. # TODO: maybe not the best way to handle this
  393. return if user.admin? && user.login == 'admin' && user.mail == 'admin@example.net'
  394. deliver_security_notification(
  395. user,
  396. sender,
  397. message: :mail_body_password_updated,
  398. title: :button_change_password,
  399. url: {controller: 'my', action: 'password'}
  400. )
  401. end
  402. # Builds a mail to user with his account activation link.
  403. def register(user, token)
  404. @token = token
  405. @url = url_for(:controller => 'account', :action => 'activate', :token => token.value)
  406. mail :to => user.mail,
  407. :subject => l(:mail_subject_register, Setting.app_title)
  408. end
  409. # Sends an mail to user with his account activation link.
  410. #
  411. # Exemple:
  412. # Mailer.deliver_register(user, token)
  413. def self.deliver_register(user, token)
  414. register(user, token).deliver_later
  415. end
  416. # Build a mail to user and the additional recipients given in
  417. # options[:recipients] about a security related event made by sender.
  418. #
  419. # Example:
  420. # security_notification(user,
  421. # sender,
  422. # message: :mail_body_security_notification_add,
  423. # field: :field_mail,
  424. # value: address
  425. # ) => Mail::Message object
  426. def security_notification(user, sender, options={})
  427. @sender = sender
  428. redmine_headers 'Sender' => sender.login
  429. @message =
  430. l(options[:message],
  431. field: (options[:field] && l(options[:field])),
  432. value: options[:value])
  433. @title = options[:title] && l(options[:title])
  434. @remote_ip = options[:remote_ip] || @sender.remote_ip
  435. @url = options[:url] && (options[:url].is_a?(Hash) ? url_for(options[:url]) : options[:url])
  436. redmine_headers 'Url' => @url
  437. mail :to => [user, *options[:recipients]].uniq,
  438. :subject => "[#{Setting.app_title}] #{l(:mail_subject_security_notification)}"
  439. end
  440. # Notifies the given users about a security related event made by sender.
  441. #
  442. # You can specify additional recipients in options[:recipients]. These will be
  443. # added to all generated mails for all given users. Usually, you'll want to
  444. # give only a single user when setting the additional recipients.
  445. #
  446. # Example:
  447. # Mailer.deliver_security_notification(users,
  448. # sender,
  449. # message: :mail_body_security_notification_add,
  450. # field: :field_mail,
  451. # value: address
  452. # )
  453. def self.deliver_security_notification(users, sender, options={})
  454. # Symbols cannot be serialized:
  455. # ActiveJob::SerializationError: Unsupported argument type: Symbol
  456. options = options.transform_values {|v| v.is_a?(Symbol) ? v.to_s : v}
  457. # sender's remote_ip would be lost on serialization/deserialization
  458. # we have to pass it with options
  459. options[:remote_ip] ||= sender.remote_ip
  460. Array.wrap(users).each do |user|
  461. security_notification(user, sender, options).deliver_later
  462. end
  463. end
  464. # Build a mail to user about application settings changes made by sender.
  465. def settings_updated(user, sender, changes, options={})
  466. @sender = sender
  467. redmine_headers 'Sender' => sender.login
  468. @changes = changes
  469. @remote_ip = options[:remote_ip] || @sender.remote_ip
  470. @url = url_for(controller: 'settings', action: 'index')
  471. mail :to => user,
  472. :subject => "[#{Setting.app_title}] #{l(:mail_subject_security_notification)}"
  473. end
  474. # Notifies admins about application settings changes made by sender, where
  475. # changes is an array of settings names.
  476. #
  477. # Exemple:
  478. # Mailer.deliver_settings_updated(sender, [:login_required, :self_registration])
  479. def self.deliver_settings_updated(sender, changes, options={})
  480. return unless changes.present?
  481. # Symbols cannot be serialized:
  482. # ActiveJob::SerializationError: Unsupported argument type: Symbol
  483. changes = changes.map(&:to_s)
  484. # sender's remote_ip would be lost on serialization/deserialization
  485. # we have to pass it with options
  486. options[:remote_ip] ||= sender.remote_ip
  487. users = User.active.where(admin: true).to_a
  488. users.each do |user|
  489. settings_updated(user, sender, changes, options).deliver_later
  490. end
  491. end
  492. # Build a test email to user.
  493. def test_email(user)
  494. @url = url_for(:controller => 'welcome')
  495. mail :to => user,
  496. :subject => 'Redmine test'
  497. end
  498. # Send a test email to user. Will raise error that may occur during delivery.
  499. #
  500. # Exemple:
  501. # Mailer.deliver_test_email(user)
  502. def self.deliver_test_email(user)
  503. raise_delivery_errors_was = self.raise_delivery_errors
  504. self.raise_delivery_errors = true
  505. # Email must be delivered synchronously so we can catch errors
  506. test_email(user).deliver_now
  507. ensure
  508. self.raise_delivery_errors = raise_delivery_errors_was
  509. end
  510. # Builds a reminder mail to user about issues that are due in the next days.
  511. def reminder(user, issues, days)
  512. @issues = issues
  513. @days = days
  514. @open_issues_url = url_for(:controller => 'issues', :action => 'index',
  515. :set_filter => 1, :assigned_to_id => 'me',
  516. :sort => 'due_date:asc')
  517. @reminder_issues_url = url_for(:controller => 'issues', :action => 'index',
  518. :set_filter => 1, :sort => 'due_date:asc',
  519. :f => ['status_id', 'assigned_to_id', "due_date"],
  520. :op => {'status_id' => 'o', 'assigned_to_id' => '=', 'due_date' => '<t+'},
  521. :v =>{'assigned_to_id' => ['me'], 'due_date' => [days]})
  522. query = IssueQuery.new(:name => '_')
  523. query.add_filter('assigned_to_id', '=', ['me'])
  524. @open_issues_count = query.issue_count
  525. mail :to => user,
  526. :subject => l(:mail_subject_reminder, :count => issues.size, :days => days)
  527. end
  528. # Sends reminders to issue assignees
  529. # Available options:
  530. # * :days => how many days in the future to remind about (defaults to 7)
  531. # * :tracker => id of tracker for filtering issues (defaults to all trackers)
  532. # * :project => id or identifier of project to process (defaults to all projects)
  533. # * :users => array of user/group ids who should be reminded
  534. # * :version => name of target version for filtering issues (defaults to none)
  535. def self.reminders(options={})
  536. days = options[:days] || 7
  537. project = options[:project] ? Project.find(options[:project]) : nil
  538. tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
  539. target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil
  540. if options[:version] && target_version_id.blank?
  541. raise ActiveRecord::RecordNotFound.new("Couldn't find Version named #{options[:version]}")
  542. end
  543. user_ids = options[:users]
  544. scope =
  545. Issue.open.where(
  546. "#{Issue.table_name}.assigned_to_id IS NOT NULL" \
  547. " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" \
  548. " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date
  549. )
  550. scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?
  551. scope = scope.where(:project_id => project.id) if project
  552. scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present?
  553. scope = scope.where(:tracker_id => tracker.id) if tracker
  554. issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).
  555. group_by(&:assigned_to)
  556. issues_by_assignee.keys.each do |assignee|
  557. if assignee.is_a?(Group)
  558. assignee.users.each do |user|
  559. issues_by_assignee[user] ||= []
  560. issues_by_assignee[user] += issues_by_assignee[assignee]
  561. end
  562. end
  563. end
  564. issues_by_assignee.each do |assignee, issues|
  565. if assignee.is_a?(User) && assignee.active? && issues.present?
  566. visible_issues = issues.select {|i| i.visible?(assignee)}
  567. visible_issues.sort!{|a, b| (a.due_date <=> b.due_date).nonzero? || (a.id <=> b.id)}
  568. reminder(assignee, visible_issues, days).deliver_later if visible_issues.present?
  569. end
  570. end
  571. end
  572. # Activates/desactivates email deliveries during +block+
  573. def self.with_deliveries(enabled = true, &block)
  574. was_enabled = ActionMailer::Base.perform_deliveries
  575. ActionMailer::Base.perform_deliveries = !!enabled
  576. yield
  577. ensure
  578. ActionMailer::Base.perform_deliveries = was_enabled
  579. end
  580. # Execute the given block with inline sending of emails if the default Async
  581. # queue is used for the mailer. See the Rails guide:
  582. # Using the asynchronous queue from a Rake task will generally not work because
  583. # Rake will likely end, causing the in-process thread pool to be deleted, before
  584. # any/all of the .deliver_later emails are processed
  585. def self.with_synched_deliveries(&block)
  586. adapter = ActionMailer::MailDeliveryJob.queue_adapter
  587. ActionMailer::MailDeliveryJob.queue_adapter = ActiveJob::QueueAdapters::InlineAdapter.new
  588. yield
  589. ensure
  590. ActionMailer::MailDeliveryJob.queue_adapter = adapter
  591. end
  592. def mail(headers={}, &block)
  593. # Add a display name to the From field if Setting.mail_from does not
  594. # include it
  595. begin
  596. mail_from = Mail::Address.new(Setting.mail_from)
  597. if mail_from.display_name.blank? && mail_from.comments.blank?
  598. mail_from.display_name =
  599. @author&.logged? ? @author.name : Setting.app_title
  600. end
  601. from = mail_from.format
  602. list_id = "<#{mail_from.address.to_s.tr('@', '.')}>"
  603. rescue Mail::Field::IncompleteParseError
  604. # Use Setting.mail_from as it is if Mail::Address cannot parse it
  605. # (probably the emission address is not RFC compliant)
  606. from = Setting.mail_from.to_s
  607. list_id = "<#{from.tr('@', '.')}>"
  608. end
  609. headers.reverse_merge! 'X-Mailer' => 'Redmine',
  610. 'X-Redmine-Host' => Setting.host_name,
  611. 'X-Redmine-Site' => Setting.app_title,
  612. 'X-Auto-Response-Suppress' => 'All',
  613. 'Auto-Submitted' => 'auto-generated',
  614. 'From' => from,
  615. 'List-Id' => list_id
  616. # Replaces users with their email addresses
  617. [:to, :cc, :bcc].each do |key|
  618. if headers[key].present?
  619. headers[key] = self.class.email_addresses(headers[key])
  620. end
  621. end
  622. # Removes the author from the recipients and cc
  623. # if the author does not want to receive notifications
  624. # about what the author do
  625. if @author&.logged? && @author.pref.no_self_notified
  626. addresses = @author.mails
  627. headers[:to] -= addresses if headers[:to].is_a?(Array)
  628. headers[:cc] -= addresses if headers[:cc].is_a?(Array)
  629. end
  630. if @author&.logged?
  631. redmine_headers 'Sender' => @author.login
  632. end
  633. if @message_id_object
  634. headers[:message_id] = "<#{self.class.message_id_for(@message_id_object, @user)}>"
  635. end
  636. if @references_objects
  637. headers[:references] = @references_objects.collect {|o| "<#{self.class.references_for(o, @user)}>"}.join(' ')
  638. end
  639. if block_given?
  640. super headers, &block
  641. else
  642. super headers do |format|
  643. format.text
  644. format.html unless Setting.plain_text_mail?
  645. end
  646. end
  647. end
  648. def self.deliver_mail(mail)
  649. return false if mail.to.blank? && mail.cc.blank? && mail.bcc.blank?
  650. begin
  651. # Log errors when raise_delivery_errors is set to false, Rails does not
  652. mail.raise_delivery_errors = true
  653. super
  654. rescue => e
  655. if ActionMailer::Base.raise_delivery_errors
  656. raise e
  657. else
  658. Rails.logger.error "Email delivery error: #{e.message}"
  659. end
  660. end
  661. end
  662. # Returns an array of email addresses to notify by
  663. # replacing users in arg with their notified email addresses
  664. #
  665. # Example:
  666. # Mailer.email_addresses(users)
  667. # => ["foo@example.net", "bar@example.net"]
  668. def self.email_addresses(arg)
  669. arr = Array.wrap(arg)
  670. mails = arr.reject {|a| a.is_a? Principal}
  671. users = arr - mails
  672. if users.any?
  673. mails += EmailAddress.
  674. where(:user_id => users.map(&:id)).
  675. where("is_default = ? OR notify = ?", true, true).
  676. pluck(:address)
  677. end
  678. mails
  679. end
  680. private
  681. # Appends a Redmine header field (name is prepended with 'X-Redmine-')
  682. def redmine_headers(h)
  683. h.compact.each {|k, v| headers["X-Redmine-#{k}"] = v.to_s}
  684. end
  685. def assignee_for_header(issue)
  686. case issue.assigned_to
  687. when User
  688. issue.assigned_to.login
  689. when Group
  690. "Group (#{issue.assigned_to.name})"
  691. end
  692. end
  693. # Singleton class method is public
  694. class << self
  695. def token_for(object, user)
  696. timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on)
  697. hash = [
  698. "redmine",
  699. "#{object.class.name.demodulize.underscore}-#{object.id}",
  700. timestamp.utc.strftime("%Y%m%d%H%M%S")
  701. ]
  702. hash << user.id if user
  703. host = Setting.mail_from.to_s.strip.gsub(%r{^.*@|>}, '')
  704. host = "#{::Socket.gethostname}.redmine" if host.empty?
  705. "#{hash.join('.')}@#{host}"
  706. end
  707. # Returns a Message-Id for the given object
  708. def message_id_for(object, user)
  709. token_for(object, user)
  710. end
  711. # Returns a uniq token for a given object referenced by all notifications
  712. # related to this object
  713. def references_for(object, user)
  714. token_for(object, user)
  715. end
  716. end
  717. def message_id(object)
  718. @message_id_object = object
  719. end
  720. def references(object)
  721. @references_objects ||= []
  722. @references_objects << object
  723. end
  724. end