JonatanEkstedt
JonatanEkstedt

Reputation: 925

Formatting smtp message header fields in Ruby

I'm trying to create a normal smtp message in Ruby:

def send_email(msg, to)
    require 'net/smtp'
    require 'tlsmail'

    from = '[email protected]'
    p = hmhmm

    msgstr = <<-END_OF_MESSAGE
    From: User <[email protected]>
    To: Jensa <[email protected]>
    Subject: Titel

    Hej PÅ dig. Inte under.   # <- swedish ;)
    END_OF_MESSAGE

    Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)

    Net::SMTP.start('smtp.gmail.com', 587, 'gmail.com', from, p, :login) do |smtp|
        smtp.send_message msgstr, from, to
    end
    puts "message sent"
end

The message is sent, but all the data except the "TO" address ends up in the "FROM" field of the message, like this:

FROM: User <[email protected]> To: Jensa Subject: Titel Hej PÅ dig. Inte under.<[email protected]>
Date: 9 February 2012 14.36.03 CET

There's nothing in the message body.

When I add a '\n' after "Titel", then all the text after is placed in the message as it should:

From:   User <[email protected]> To: Jensa Subject: Titel <[email protected]>
Date:   9 februari 2012 14.36.03 CET

      Hej PÅ dig. Inte under.

But still the "TO" address is not visible and it's all in the FROM field.

What's the problem?

Upvotes: 3

Views: 1382

Answers (1)

SimonMayer
SimonMayer

Reputation: 4916

You MUST use a CRLF to separate each line.

I guess your lines are currently only being separated by either "\r" or "\n" - not both. Try:

msgstr = [
  "From: User <[email protected]>",
  "To: Jensa <[email protected]>",
  "Subject: Titel",
  "",
  "Hej PÅ dig. Inte under."   # <- swedish ;)
].join("\r\n")

Upvotes: 2

Related Questions