TMail is designed to be an RFC compatible library. The goal of TMail is to allow you to create emails programatically without having to know about the RFCs or how they work, or what their standards are.
When you use TMail, you need to create a TMail object. There are
three ways you can do this, the first is by parsing a string supplied
to TMail, the second is by loading the mail object from a file, and
the third is by opening up a port to whatever mail source you want.
For example:
require 'tmail' mail = TMail::Mail.parse(string) # from String
require 'tmail' mail = TMail::Mail.load(filename) # from file
The third way to get TMail::Mail object is using the "port".
"port" is the abstruction of mail sources, e.g. strings or file names.
You can get ports by using mail loaders (TMail::*Loader classes).
Here's simple example:
require 'tmail' loader = TMail::MhLoader.new( '/home/aamine/Mail/inbox' ) loader.each_port do |port| mail = TMail::Mail.new(port) # .... end
This lets you cycle through your messages in the inbox
Once you have the Email loaded, you can now access the various parts
of the email, using various methods on the now instantiated TMail::Mail
object.
For example...
require 'tmail' mail = TMail::Mail.parse( 'To: Minero Aoki <aamine@loveruby.net>' ) p mail.to # => ["aamine@loveruby.net"]
p mail.subject
p mail.body
For more information, see the RDoc index and the TMail::Mail class specifically.
TMail also supports MIME multipart mails.
If mail is multipart mail, Mail#multipart? returns true,
and Mail#parts contains an array of parts (TMail::Mail object).
require 'tmail' mail = TMail::Mail.parse( multipart_mail_string ) if mail.multipart? then mail.parts.each do |m| puts m.main_type end end
Creating an email is just as easy:
require 'tmail' # Example 1: create mail only in memory mail = TMail::Mail.new # Example 2: create mail on mailbox (on disk) loader = TMail::MhLoader.new('/home/aamine/Mail/drafts') mail = TMail::Mail.new( loader.new_port )
Then fill headers and body.
mail.to = 'test@loveruby.net' mail.from = 'Minero Aoki <aamine@loveruby.net>' mail.subject = 'test mail' mail.date = Time.now mail.mime_version = '1.0' mail.set_content_type 'text', 'plain', {'charset'=>'iso-2022-jp'} mail.body = 'This is test mail.'
At last, convert mail object to string.
str = mail.to_s
If you want to write mails against files directly (without intermediate string), use Mail#write_back.
mail.write_back
Right now, TMail does not touch the body of the mail message, for example, it doesn't encode, decode, handle character sets etc. It only handles the message and headers and gives you access to read and write the mail body.
Plans for future versions are to allow better handling of the mail body, auto decode Base64 and handling attachments in a better way.
Go to the online manual to find out how to use it all, or if you are stuck you can join the TMail-Talk mailing list and ask your question there.