don't send more than 1 reply per day to auto-generated emails

This commit is contained in:
Régis Hanol
2016-06-28 16:42:05 +02:00
parent 1411eedad3
commit 214f5bff5c
8 changed files with 30 additions and 94 deletions

View File

@ -15,16 +15,14 @@ module Email
receiver = Email::Receiver.new(@mail)
receiver.process!
rescue Email::Receiver::BouncedEmailError => e
# never reply to bounced emails
log_email_process_failure(@mail, e)
set_incoming_email_rejection_message(receiver.incoming_email, I18n.t("emails.incoming.errors.bounced_email_error"))
rescue Email::Receiver::AutoGeneratedEmailReplyError => e
log_email_process_failure(@mail, e)
set_incoming_email_rejection_message(receiver.incoming_email, I18n.t("emails.incoming.errors.auto_generated_email_reply"))
rescue => e
log_email_process_failure(@mail, e)
rejection_message = handle_failure(@mail, e)
if rejection_message.present? && receiver && (incoming_email = receiver.incoming_email)
incoming_email = receiver.try(:incoming_email)
rejection_message = handle_failure(@mail, e, incoming_email)
if rejection_message.present?
set_incoming_email_rejection_message(incoming_email, rejection_message.body.to_s)
end
end
@ -32,7 +30,7 @@ module Email
private
def handle_failure(mail_string, e)
def handle_failure(mail_string, e, incoming_email)
message_template = case e
when Email::Receiver::EmptyEmailError then :email_reject_empty
when Email::Receiver::NoBodyDetectedError then :email_reject_empty
@ -67,10 +65,6 @@ module Email
template_args[:rate_limit_description] = e.description
end
if message_template == :email_reject_auto_generated
template_args[:mark_as_reply_to_auto_generated] = true
end
if message_template
# inform the user about the rejection
message = Mail::Message.new(mail_string)
@ -79,7 +73,11 @@ module Email
template_args[:site_name] = SiteSetting.title
client_message = RejectionMailer.send_rejection(message_template, message.from, template_args)
Email::Sender.new(client_message, message_template).send
# don't send more than 1 reply per day to auto-generated emails
if !incoming_email.try(:is_auto_generated) || can_reply_to_auto_generated?(message.from)
Email::Sender.new(client_message, message_template).send
end
else
Rails.logger.error("Unrecognized error type (#{e}) when processing incoming email\n\nMail:\n#{mail_string}")
end
@ -87,6 +85,17 @@ module Email
client_message
end
def can_reply_to_auto_generated?(email)
key = "auto_generated_reply:#{email}:#{Date.today}"
if $redis.setnx(key, "1")
$redis.expire(key, 25.hours)
true
else
false
end
end
def set_incoming_email_rejection_message(incoming_email, message)
incoming_email.update_attributes!(rejection_message: message)
end