0

In my Ruby on Rails application I have a Mailer class that sends email with a user defined from header:

def hello_email(user)
  @user = user
  from_email = %("#{@user.name}" <#{@user.email}>)
  to_email = "foo@bar.com"
  mail(from: from_email, to: to_email, subject: 'Hello everybody')
end

I am using a slightly different version of this code and have them delivered with Sucker Punch.

The problem I encountered is that the mailer method silently fails when @user.name is malformatted, e.g. contains a comma, producing a Net::SMTPSyntaxError 504 5.5.2 in the logs.

What would be the best way to prevent that? I'd like to write a validation method in the User class that blacklists or whitelists certain characters but I don't know which ones. The only character causing problems so far has been a comma. And it was quite different to track down.

Thanks for any help.

Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • 1
    Does the email send without the full name stuff, just using the email, or using a 'clean' full name? I thought `504 5.5.2` was something to do with the 'from email' or your smtp server being bad or something, though I could be wrong there – Simple Lime Jul 15 '17 at 08:31
  • @SimpleLime: Yes, you are absolutely right. It's the `from` address that is causing trouble, not the `to` address. I corrected my initial post. Thanks. – Tintin81 Jul 15 '17 at 08:41

2 Answers2

1

My best guess is that you have to detect for , and ; only, and what made me conclude it is that if you try to compose an email (e.g. gmail), you start typing name in To section, and as soon as you type , or ; it considers it as a delimiter. so the regex is pretty simple

/[,;]/

UPDATE

Found this supporting answer here

Md. Farhan Memon
  • 6,055
  • 2
  • 11
  • 36
  • This partly solves the problem, thank you. However, in the end I came up with an even cleaner solution (see my answer). – Tintin81 Jul 15 '17 at 09:28
0

OK, I managed to find the solution myself.

This is the old code inside my User model:

  def sender
    display_name = profile.company_name? ? profile.company_name : name
    "#{display_name} (via #{APP_NAME})<#{NO_REPLY_EMAIL}>"
  end

This is the corrected version:

  def sender
    display_name = profile.company_name? ? profile.company_name : name
    %("#{display_name} (via #{APP_NAME})" <#{NO_REPLY_EMAIL}>)
  end

The key is to enclose the display name in double quotes.

Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • In future questions you should try posting your code that's causing the problem (or match it more closely). Your example of the problem in your question has the double quotes around the name. Could've told you that was the problem an hour ago if we had seen this method – Simple Lime Jul 15 '17 at 09:42