4

I'm trying to send email with a Ruby script, but my proof of concept isn't working. I can telnet to the mail server and send mail that way, but this script causes the mail server to raise an error: 501 5.5.4 Invalid Address

#!/usr/bin/ruby

require 'net/smtp'

def send_email(to, subject = "", body = "")
    from = "my@email.com"
    body= "From: #{from}\r\nTo: #{to}\r\nSubject: #{subject}\r\n\r\n#{body}\r\n"

    Net::SMTP.start('192.168.10.213', 25, '192.168.0.218') do |smtp|
        smtp.send_message body, from, to
    end
end

send_email "my@email.com", "test", "blah blah blah"

In my actual script, my@email.com is a valid email. 192.168.10.213 is the mail server and 192.168.0.218 is my local ip. Note that I'm running windows xp, and the mail server is an exchange server.

I don't understand why telnet works with the same values, but this script raises the invalid address error.

Can somebody help me?

EDIT: The above code now works fine, I originally left out the commas in the final method call. I feel like an idiot.

4 Answers 4

1

Make sure your actual email address does not contain invalid characters. For example, see this question.

2
  • Thanks, but both my machine name and my email address are perfectly valid, no odd characters, no leading or trailing white-space or dots. My machine name does have a dash in it though... it's a hassle to change my computer name, as I'm in a corporate network. Could the dash be the problem? Remember, telnet works! Jul 29, 2009 at 15:06
  • Dash should be fine, though underscore isn't valid for domains. You might need to look at the SMTP traffic to see what the server is actually seeing - it may not be what you think it's seeing. Jul 29, 2009 at 15:35
1

I'd recommend Action Mailer for sending mails with Ruby. See a snippet here.

1
  • I'd rather use Net::SMTP ... I don't need all that jazz. Using anything that's not in the ruby core is my last resort (ie Action Mailer or TMail or similar) Jul 29, 2009 at 15:25
1

Can you believe it? I feel like an idiot, I'm just missing commas in the method call...

send_email "my@email.com", "test", "blah blah blah"

I'm embarrassed.

Anyway, the above code works great if anyone is interested. Just don't leave out the commas like I did.

1

There is a bug in your code. A malicious user could insert more headers into your email by using newlines in the subject.

1
  • Good catch. This code was only used as a locally run script for a one time use batch job, so I didn't consider that kind of security. It's still a good point though for anyone else who may want to use this code. Thanks. Aug 5, 2010 at 4:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.