1

I have a form with a text field where users can input multiple email addresses. The problem is, these email addresses are formatted in many different ways. For instance:

"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>

Right now, I separate them using:

emails = params[:invite][:invite_emails].split(', ')
emails.each do |email|
  # send_email
end

How could I get all the emails even though they're formatted differently?

alejorivera
  • 935
  • 1
  • 10
  • 25

1 Answers1

2

There is no absolute way of parsing emails. But we can try to cover some good grounds:

s = '"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>'
s.scan(/\w+@\w+\.\w+/)
#=> ["bob@company.com", "joe@company.com", "john@company.com"]

This will cover the gTLDs as well:

s = '"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com> smith@mango.co.uk'
s.scan(/\w+@\w+\.\w+[\.\w]{0,4}/)
#=> ["bob@company.com", "joe@company.com", "john@company.com", "smith@mango.co.uk"]

If you still have other special case, you'll just have to tweak the Regex a bit.

Babar Al-Amin
  • 3,939
  • 1
  • 16
  • 20