Ever wondered if you can use gmail’s web UI to send emails using Ruby? The answer is YES!

Why use their web UI instead of SMTP, you may ask? Normally I would say don’t. I would tell you to skip gmail entirely and use a service like AuthSMTP to send your emails reliably. However, there are some cases where punching through email filters takes a little extra juice. In those cases, gmail’s web UI can be just the remedy. For privacy reasons, gmail’s web interface masks the sending IP address. All the recipient can see is that the message originated from gmail. If your sending IP address has been used for spam in the past, this approach can help with email delivery. This technique is indistinguishable from using gmail’s web UI in a browser.

Gmail’s modern web UI requires a JavaScript engine, which makes it a non-starter for WWW::Mechanize scripting. But gmail also offers a fallback ‘HTML-only’ mode works for our purposes.

Here is a Ruby script using WWW::Mechanize that will send emails programmatically through gmail’s web interface.

agent = Mechanize.new
agent.user_agent_alias = 'Linux Mozilla'
page = agent.get 'http://www.gmail.com'

# #log into gmail
form = page.forms.first
form.Email = 'my_address@gmail.com'
form.Passwd = 'password'
page = agent.submit(form, form.buttons.first)

page = agent.click page.links.find { |l| l.text =~ /basic HTML/i }
page = agent.click page.links.find { |l| l.text =~ /compose/i }

form = page.forms[1]

form.to = 'example@example.com'

form.subject = 'test subject'

form.body = < "Hi,

I would like to email you.

"
EOF
page = agent.submit(form, form.buttons.first)

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2011 Ben Allfree :: Painless Programming