Last active
November 13, 2020 09:20
-
-
Save hmnhf/da95ecd81240bbe96836 to your computer and use it in GitHub Desktop.
Mandrillapp invalid sender characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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} <[email protected]>" | |
subject 'A transactional email from Mandrill!' | |
end | |
rescue Net::SMTPServerBusy | |
invalid_chrs.push(chr) | |
end | |
end | |
# => ["\"", "(", ",", ":", ";", "<", ">", "["] |
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
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
Thank you for this, you have probably saved me a few hours and an headache.