Skip to content

Instantly share code, notes, and snippets.

@hmnhf
Last active November 13, 2020 09:20
Show Gist options
  • Save hmnhf/da95ecd81240bbe96836 to your computer and use it in GitHub Desktop.
Save hmnhf/da95ecd81240bbe96836 to your computer and use it in GitHub Desktop.
Mandrillapp invalid sender characters
# I was encountering this exception: Net::SMTPServerBusy: 401 4.1.7 Bad sender address syntax
# First I searched to see if there's any documentation around this issue but didn't find anything,
# so I wrote this snippet to find those invalid characters.
require 'mail'
Mail.defaults do
delivery_method :smtp, {
port: 25,
address: "smtp.mandrillapp.com",
user_name: ENV["MANDRILL_USERNAME"],
password: ENV["MANDRILL_PASSWORD"]
}
end
(32..255).each_with_object([]) do |codepoint, invalid_chrs|
chr = codepoint.chr
begin
Mail.deliver do
to ENV["MYEMAIL"]
from "John Doe #{chr} <john@doe.com>"
subject 'A transactional email from Mandrill!'
end
rescue Net::SMTPServerBusy
invalid_chrs.push(chr)
end
end
# => ["\"", "(", ",", ":", ";", "<", ">", "["]
@aliou
Copy link

aliou commented Sep 2, 2015

Thank you for this, you have probably saved me a few hours and an headache.

@ghiculescu
Copy link

i added this inside ApplicationMailer:

  def mail(headers = {}, &block)
    if block_given?
      super
    else
      # https://gist.github.com/hmnhf/da95ecd81240bbe96836
      # strip invalid characters from email headers
      [:from, :reply_to, :to].each do |param|
        name = headers.delete(param)
        email_match = name.match(/ <[^<>]+@[^<>]+>$/)
        if email_match
          sender = name.sub(email_match[0], '')
          headers[param] = "#{sender.tr('"(,:;<>[', '')} #{email_match[0]}"
        else
          headers[param] = name
        end
      end
      super(headers)
    end
  end

@goofansu
Copy link

goofansu commented Aug 3, 2020

Thank you for the gist, saving a lot of time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment