begin require 'email_format' rescue LoadError raise "You need to add gem 'email_format' to your Gemfile if you wish to use it." end # # Objects that emails can be sent too... # module EmailAble extend ActiveSupport::Concern include App47Logger def self.included(base) base.class_eval do field :email, type: String field :email_bounced_at, type: Time field :email_bounce_reason, type: String field :unconfirmed_email, type: String field :email_enabled, type: Boolean, default: true # # Validations # validates :email, email_format: { strict: true }, allow_blank: true # # Callbacks # before_validation :downcase_email end end # # Support legacy apps with old name # def email_bounce_date(date = nil) self.email_bounced_at = date if date.present? email_bounced_at end # # Is this a valid email to send to? # def valid_email? email_enabled? && !email_bounced? end # # Has the email bounced? # def email_bounced? email_bounced_at.present? end # # Set the email to a bounced status with the given reason # def bounced(reason) set email_bounced_at: Time.now.utc, email_bounce_reason: reason end # # Reset the bounced email # def reset_bounce_status(current_member = nil) return unless SystemConfiguration.mail_gun_configured? && email_bounced? reset_url = "https://api.mailgun.net/v3/#{SystemConfiguration.smtp_domain}/bounces/#{CGI.escape(email)}" RestClient.delete(reset_url, user: 'api', password: SystemConfiguration.mailgun_api_key) rescue RestClient::Exception => error log_error "Unable to reset email bounce status: #{inspect}", error ensure if current_member.present? update_and_log current_member, email_bounced_at: nil, email_bounce_reason: nil else set email_bounced_at: nil, email_bounce_reason: nil end end # # Return the gravatar URL based on email address # def gravatar_url(size = '32', default = 'mm') self.email ||= 'noone@abc.com' if SystemConfiguration.fips_mode? "https://www.gravatar.com/avatar/#{Digest::SHA2.hexdigest(email)}?s=#{size}&d=#{default}" else "https://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(email)}?s=#{size}&d=#{default}" end end private # # Make sure emails are always downcased # def downcase_email self.email = email.strip.downcase if email.present? end end