TMail Basics

TMail is 90% RFC compatible (not 100%) mail library. You can use TMail to get data from internet mail (email) and write data to mail.

Getting information from email

To get information from email, try this steps:

  1. load mail from anywhere
  2. access through facade interfaces defined in TMail::Mail class.

Here's simple example.

require 'tmail'
mail = TMail::Mail.load( 'Mailbox/inbox/1' )
puts mail.from
puts mail.subject

"Mailbox/inbox/1" is a file that includes just one mail as plain text (like Mh mailbox).

If you want to create mail object from String, try this:

require 'tmail'
mail = TMail::Mail.parse( "From: aamine@loveruby.net\nSubject: tmail test\n...." )
puts mail.from
puts mail.subject

For more methods of TMail::Mail class, see Mail class reference.

Loading Mails from famous Mailboxes

There're many famous mailbox. For example Mh, UNIX mbox, maildir, rmail, and so on. TMail currently supports Mh, maildir (still on testing) and UNIX mbox.

require 'tmail'
TMail::MhLoader.new( '/home/aamine/Mailbox' ).each_mail do |port|
  mail = TMail::Mail.new(port)
  # do anything...
end

PORT is the object which represents the source location of the mail. For example files or strings. MhLoader loads FilePort objects. For more details, see Loader class reference.

Saving Mails to File

Example: create the mail on the memory and write it to file.

require 'tmail'

mail = TMail::Mail.new
mail.from = 'anybody@anywhere.com'
mail.to = 'aamine@loveruby.net'
mail.subject = 'I found tmail bug!'
File.open( 'save', 'w' ) {|f|
  mail.encoded "\n", 'j', f
}

Example 2: create the mail connected to the mailbox

require 'tmail'

port = TMail::MhLoader.new( 'Mailbox/draft' ).new_port
mail = TMail::Mail.new( port )
mail.from = 'anybody@anywhere.com'
mail.to = 'aamine@loveruby.net'
mail.subject = 'I found tmail bug!'
mail.write_back

Copyright (c) 1998-2001 Minero Aoki <aamine@loveruby.net>