class MailIdentity < ApplicationRecord include Auditable encrypts :smtp_password require "openssl" has_many :mailings, dependent: :restrict_with_exception ENCRYPTIONS = Catalog::MAIL_ENCRYPTIONS.keys.freeze validates :name, :from_name, :from_email, :smtp_host, :smtp_port, presence: true validates :from_email, format: { with: URI::MailTo::EMAIL_REGEXP } validates :reply_to, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_blank: true validates :smtp_port, numericality: { in: 1..65535 } validates :encryption, inclusion: { in: ENCRYPTIONS } validates :smtp_authentication, inclusion: { in: Catalog::MAIL_AUTH_METHODS.keys } scope :active, -> { where(active: true) } scope :ordered, -> { order(:name) } def from_header %(#{from_name} <#{from_email}>) end def smtp_settings settings = { address: smtp_host, port: smtp_port, enable_starttls_auto: encryption == "starttls", ssl: encryption == "tls", openssl_verify_mode: verify_ssl? ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE } if smtp_username.present? settings[:user_name] = smtp_username settings[:password] = smtp_password settings[:authentication] = smtp_authentication.to_sym end settings end end