smtp.rb 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # Copyright (C) 2012-2025 Zammad Foundation, https://zammad-foundation.org/
  2. class Channel::Driver::Smtp < Channel::Driver::BaseEmailOutbound
  3. =begin
  4. instance = Channel::Driver::Smtp.new
  5. instance.send(
  6. {
  7. host: 'some.host',
  8. port: 25,
  9. enable_starttls_auto: true, # optional
  10. openssl_verify_mode: 'none', # optional
  11. user: 'someuser',
  12. password: 'somepass'
  13. authentication: nil, # nil, autodetection - to use certain schema use 'plain', 'login', 'xoauth2' or 'cram_md5'
  14. },
  15. mail_attributes,
  16. notification
  17. )
  18. =end
  19. def deliver(options, attr, notification = false)
  20. # return if we run import mode
  21. return if Setting.get('import_mode')
  22. options = prepare_options(options, attr)
  23. attr = prepare_message_attrs(attr)
  24. smtp_params = build_smtp_params(options)
  25. Certificate::ApplySSLCertificates.ensure_fresh_ssl_context if options[:ssl] || options[:enable_starttls_auto]
  26. deliver_mail(attr, notification, :smtp, smtp_params)
  27. end
  28. def prepare_options(options, attr)
  29. # set smtp defaults
  30. if !options.key?(:port) || options[:port].blank?
  31. options[:port] = 25
  32. end
  33. if !options.key?(:ssl) && options[:port].to_i == 465
  34. options[:ssl] = true
  35. end
  36. if !options.key?(:domain)
  37. # set fqdn, if local fqdn - use domain of sender
  38. fqdn = Setting.get('fqdn')
  39. if fqdn =~ %r{(localhost|\.local^|\.loc^)}i && (attr['from'] || attr[:from])
  40. domain = Mail::Address.new(attr['from'] || attr[:from]).domain
  41. if domain
  42. fqdn = domain
  43. end
  44. end
  45. options[:domain] = fqdn
  46. end
  47. if !options.key?(:enable_starttls_auto)
  48. options[:enable_starttls_auto] = true
  49. end
  50. options
  51. end
  52. def build_smtp_params(options)
  53. ssl_verify_mode = if options[:openssl_verify_mode].present?
  54. options[:openssl_verify_mode]
  55. else
  56. options.fetch(:ssl_verify, true) ? 'peer' : 'none'
  57. end
  58. smtp_params = {
  59. openssl_verify_mode: ssl_verify_mode,
  60. address: options[:host],
  61. port: options[:port],
  62. domain: options[:domain],
  63. enable_starttls_auto: options[:enable_starttls_auto],
  64. open_timeout: DEFAULT_OPEN_TIMEOUT,
  65. read_timeout: DEFAULT_READ_TIMEOUT,
  66. }
  67. # set ssl if needed
  68. if options[:ssl].present?
  69. smtp_params[:ssl] = options[:ssl]
  70. end
  71. # add authentication only if needed
  72. if options[:user].present?
  73. smtp_params[:user_name] = options[:user]
  74. smtp_params[:password] = options[:password]
  75. smtp_params[:authentication] = options[:authentication]
  76. end
  77. smtp_params
  78. end
  79. end