Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting smtp message header fields in Ruby

Tags:

ruby

smtp

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?

like image 473
JonatanEkstedt Avatar asked Apr 23 '26 12:04

JonatanEkstedt


1 Answers

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")
like image 167
SimonMayer Avatar answered Apr 26 '26 01:04

SimonMayer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!