# imap-append-example.rb
# requires TMail library (http://i.loveruby.net/en/prog/tmail.html)
require 'net/imap'
require 'tmail'
IMAP_HOST = 'imap.example.com'
IMAP_USER = 'user'
IMAP_PASSWORD = 'password'
IMAP_MAILBOX = 'INBOX.scratch'
# Connect and authenticate
imap = Net::IMAP.new(IMAP_HOST)
imap.login(IMAP_USER, IMAP_PASSWORD)
# Create the target folder if needed
imap.create(IMAP_MAILBOX) unless imap.list(IMAP_MAILBOX, "*")
# Insure the message timestamp will be consistent
created = Time.now
# Create our email object
msg = TMail::Mail.new
msg.from = 'ruby@example.com'
msg.to = 'me@example.com'
msg.date = created
msg.subject = 'Inserted by Ruby'
# Finally, append the message to the mailbox. The line ending
# argument is needed to make sure the TMail::Mail#to_s method
# doesn't generate invalid, "\n"-terminated lines
# Also, you can remove the :Seen symbol from the flag list to
# make the message appear unread in other IMAP clients
imap.append(IMAP_MAILBOX, msg.to_s("\r\n"), [:Seen], created)
Recent Comments