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

mailer.rb 27KB

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