Posted by

ITEM TILE – File Size: 10.2K

A Really Ruby Mail Library

Mail Build Status


Mail is an internet library for Ruby that is designed to handle emailgeneration, parsing and sending in a simple, rubyesque manner.

The purpose of this library is to provide a single point of access to handleall email functions, including sending and receiving email. All networktype actions are done through proxy methods to Net::SMTP, Net::POP3 etc.

Built from my experience with TMail, it is designed to be a pure rubyimplementation that makes generating, sending and parsing email a nobrainer.

It is also designed from the ground up to work with the more modern versionsof Ruby. This is because Ruby > 1.9 handles text encodings much more wonderfullythan Ruby 1.8.x and so these features have been taken full advantage of in thislibrary allowing Mail to handle a lot more messages more cleanly than TMail.Mail does run on Ruby 1.8.x… it’s just not as fun to code.

Finally, Mail has been designed with a very simple object oriented systemthat really opens up the email messages you are parsing, if you know whatyou are doing, you can fiddle with every last bit of your email directly.

You can contribute to this library

Yes, you! Mail is used in countless apps by people around the world. It is,like all open source software, a labour of love borne from our free time.If you would like to say thanks, please dig in and contribute alongside us!Triage and fix GitHub issues, improveour documentation, add new features—up to you! Thank you for pitching in.



Mail supports Ruby 1.8.7+, including JRuby and Rubinius.

Every Mail commit is tested by Travis on all supported Ruby versions.


If you want to discuss mail with like minded individuals, please subscribe tothe Google Group.

Current Capabilities of Mail

  • RFC5322 Support, Reading and Writing
  • RFC6532 Support, reading UTF-8 headers
  • RFC2045-2049 Support for multipart email
  • Support for creating multipart alternate email
  • Support for reading multipart/report email & getting details from such
  • Wrappers for File, Net/POP3, Net/SMTP
  • Auto-encoding of non-US-ASCII bodies and header fields

Mail is RFC5322 and RFC6532 compliant now, that is, it can parse US-ASCII and UTF-8email and generate US-ASCII email. There are a few obsoleted email syntax thatit will have problems with, but it also is quite robust, meaning, if it finds somethingit doesn’t understand it will not crash, instead, it will skip the problem and keepparsing. In the case of a header it doesn’t understand, it will initialise the headeras an optional unstructured field and continue parsing.

This means Mail won’t (ever) crunch your data (I think).

You can also create MIME emails. There are helper methods for making amultipart/alternate email for text/plain and text/html (the most common pair)and you can manually create any other type of MIME email.


Next TODO:

  • Improve MIME support for character sets in headers, currently works, mostly, needsrefinement.

Testing Policy

Basically… we do BDD on Mail. No method gets written in Mail without acorresponding or covering spec. We expect as a minimum 100% coveragemeasured by RCov. While this is not perfect by any measure, it is prettygood. Additionally, all functional tests from TMail are to be passing beforethe gem gets released.

It also means you can be sure Mail will behave correctly.

API Policy

No API removals within a single point release. All removals to be deprecated withwarnings for at least one MINOR point release before removal.

Also, all private or protected methods to be declared as such – though this is still I/P.


Installation is fairly simple, I host mail on rubygems, so you can just do:

# gem install mail


If you didn’t know, handling encodings in Emails is not as straight forward as youwould hope.

I have tried to simplify it some:

  1. All objects that can render into an email, have an #encoded method. Encoded willreturn the object as a complete string ready to send in the mail system, that is,it will include the header field and value and CRLF at the end and wrapped asneeded.

  2. All objects that can render into an email, have a #decoded method. Decoded willreturn the object’s “value” only as a string. This means it will not includethe header fields (like ‘To:’ or ‘Subject:’).

  3. By default, calling #tos on a container object will call its encodedmethod, while #tos on a field object will call its decoded method.So calling #tos on a Mail object will return the mail, all encodedready to send, while calling #tos on the From field or the body willreturn the decoded value of the object. The header object of Mail is considered acontainer. If you are in doubt, call #encoded, or #decodedexplicitly, this is safer if you are not sure.

  4. Structured fields that have parameter values that can be encoded (e.g. Content-Type) willprovide decoded parameter values when you call the parameter names as methods againstthe object.

  5. Structured fields that have parameter values that can be encoded (e.g. Content-Type) willprovide encoded parameter values when you call the parameter names through theobject.parameters[''] method call.


Please do! Contributing is easy in Mail. Please read the document for more info


All major mail functions should be able to happen from the Mail module.So, you should be able to just require 'mail' to get started.

Making an email

“`rubymail = do from ‘’ to ‘’ subject ‘This is a test email’ body‘body.txt’)end

mail.to_s #=> “From: mikel@test.lindsaar.netrnTo: you@…“`

Making an email, have it your way:

“`rubymail = do body‘body.txt’)end

mail[‘from’] = ‘’mail[:to] = ‘’mail.subject = ‘This is a test email’

mail.header[‘X-Custom-Header’] = ‘custom value’

mail.to_s #=> “From: mikel@test.lindsaar.netrnTo: you@…“`

Don’t Worry About Message IDs:

“`rubymail = do to ‘’ body ‘Some simple body’end

mail.tos =~ /Message-ID: <[dw]+@.+.mail/ #=> 27“`

Mail will automatically add a Message-ID field if it is missing andgive it a unique, random Message-ID along the lines of:

Or do worry about Message-IDs:

“`rubymail = do to ‘’ message_id ‘‘ body ‘Some simple body’end

mail.to_s =~ /Message-ID: #=> 27“`

Mail will take the message_id you assign to it trusting that you knowwhat you are doing.

Sending an email:

Mail defaults to sending via SMTP to local host port 25. If you have asendmail or postfix daemon running on this port, sending email is aseasy as:

rubyMail.deliver do from '' to '' subject 'Here is the image you wanted' body'body.txt') add_file '/full/path/to/somefile.png'end


“`rubymail = do from ‘’ to ‘’ subject ‘Here is the image you wanted’ body‘body.txt’) add_file :filename => ‘somefile.png’, :content =>‘/somefile.png’)end


Sending via sendmail can be done like so:

“`rubymail = do from ‘’ to ‘’ subject ‘Here is the image you wanted’ body‘body.txt’) add_file :filename => ‘somefile.png’, :content =>‘/somefile.png’)end

mail.delivery_method :sendmail


Sending via smtp (for example to mailcatcher)“`ruby

Mail.defaults do delivery_method :smtp, address: “localhost”, port: 1025end“`

Exim requires its own delivery manager, and can be used like so:

“`rubymail.delivery_method :exim, :location => “/usr/bin/exim”


Mail may be “delivered” to a logfile, too, for development and testing:


Delivers by logging the encoded message to $stdout

mail.delivery_method :logger

Delivers to an existing logger at :debug severity

mail.deliverymethod :logger, logger: otherlogger, severity: :debug“`

Getting Emails from a POP Server:

You can configure Mail to receive email using retriever_methodwithin Mail.defaults:

rubyMail.defaults do retriever_method :pop3, :address => "", :port => 995, :user_name => '', :password => '', :enable_ssl => trueend

You can access incoming email in a number of ways.

The most recent email:

rubyMail.all #=> Returns an array of all emailsMail.first #=> Returns the first unread emailMail.last #=> Returns the last unread email

The first 10 emails sorted by date in ascending order:

rubyemails = Mail.find(:what => :first, :count => 10, :order => :asc)emails.length #=> 10

Or even all emails:

rubyemails = Mail.allemails.length #=> LOTS!

Reading an Email

“`rubymail =‘/path/to/message.eml’)

mail.envelopefrom #=> ‘’mail.from.addresses #=> [‘’, ‘’]mail.sender.address #=> ‘’ #=> ‘’ #=> ‘’mail.subject #=> “This is the subject” #=> ’21 Nov 1997 09:55:06 -0600’mail.message_id #=> ‘‘mail.decoded #=> ‘This is the body of the email…“`

Many more methods available.

Reading a Multipart Email

“`rubymail =‘multipart_email’)

mail.multipart? #=> #=> 2mail.body.preamble #=> “Text before the first part”mail.body.epilogue #=> “Text after the last part” { |p| p.contenttype } #=> [‘text/plain’, ‘application/pdf’] { |p| p.class } #=> [Mail::Message, Mail::Message][0].contenttypeparameters #=> {‘charset’ => ‘ISO-8859-1’}[1].contenttype_parameters #=> {‘name’ => ‘my.pdf’}“`

Mail generates a tree of parts. Each message has many or no parts. Each partis another message which can have many or no parts.

A message will only have parts if it is a multipart/mixed or multipart/relatedcontent type and has a boundary defined.

Testing and Extracting Attachments

rubymail.attachments.each do | attachment | # Attachments is an AttachmentsList object containing a # number of Part objects if (attachment.content_type.start_with?('image/')) # extracting images for example... filename = attachment.filename begin + filename, "w+b", 0644) {|f| f.write attachment.decoded} rescue => e puts "Unable to save data for #{filename} because #{e.message}" end endend

Writing and Sending a Multipart/Alternative (HTML and Text) Email

Mail makes some basic assumptions and makes doing the common thing assimple as possible…. (asking a lot from a mail library)

“`rubymail = Mail.deliver do to ‘’ from ‘Mikel Lindsaar‘ subject ‘First multipart email sent with Mail’

text_part do body ‘This is plain text’ end

htmlpart do contenttype ‘text/html; charset=UTF-8’ body ‘

This is HTML

‘ endend“`

Mail then delivers the email at the end of the block and returns theresulting Mail::Message object, which you can then inspect if youso desire…

“`puts mail.to_s #=>

To: Mikel Lindsaar First multipart email sent with MailContent-Type: multipart/alternative; boundary=–==mimepart4a914f0c911be_6f0f1ab8026659Message-ID: 4a914f12ac7e_6f0f1ab80267d1@baci.local.mailDate: Mon, 24 Aug 2009 00:15:46 +1000Mime-Version: 1.0Content-Transfer-Encoding: 7bit

—-==mimepart4a914f0c911be_6f0f1ab8026659Content-ID: 4a914f12c8c4_6f0f1ab80268d6@baci.local.mailDate: Mon, 24 Aug 2009 00:15:46 +1000Mime-Version: 1.0Content-Type: text/plainContent-Transfer-Encoding: 7bit

This is plain text—-==mimepart4a914f0c911be_6f0f1ab8026659Content-Type: text/html; charset=UTF-8Content-ID: 4a914f12cf86_6f0f1ab802692c@baci.local.mailDate: Mon, 24 Aug 2009 00:15:46 +1000Mime-Version: 1.0Content-Transfer-Encoding: 7bit

This is HTML


Mail inserts the content transfer encoding, the mime version,the content-IDs and handles the content-type and boundary.

Mail assumes that if your text in the body is only us-ascii, that yourtransfer encoding is 7bit and it is text/plain. You can override thisby explicitly declaring it.

Making Multipart/Alternate, Without a Block

You don’t have to use a block with the text and html part included, youcan just do it declaratively. However, you need to add Mail::Parts toan email, not Mail::Messages.

“`rubymail = do to ‘’ from ‘Mikel Lindsaar‘ subject ‘First multipart email sent with Mail’end

text_part = do body ‘This is plain text’end

htmlpart = do contenttype ‘text/html; charset=UTF-8’ body ‘

This is HTML


mail.textpart = textpartmail.htmlpart = htmlpart“`

Results in the same email as done using the block form

Getting Error Reports from an Email:

“`ruby@mail =‘/path/to/bounce_message.eml’)

@mail.bounced? #=> true@mail.finalrecipient #=> rfc822; #=> failed@mail.errorstatus #=> 5.5.0@mail.diagnostic_code #=> smtp;550 Requested action not taken: mailbox unavailable@mail.retryable? #=> false“`

Attaching and Detaching Files

You can just read the file off an absolute path, Mail will tryto guess the mime_type and will encode the file in Base64 for you.

ruby@mail ="/path/to/file.jpg") #=> #=> 'base64'@mail.attachments.first.mime_type #=> 'image/jpg'@mail.attachments.first.filename #=> 'file.jpg'@mail.attachments.first.decoded =='/path/to/file.jpg') #=> true

Or You can pass in filedata and give it a filename, again, mailwill try and guess the mimetype for you.

ruby@mail =['myfile.pdf'] ='path/to/myfile.pdf') #=> true@mail.attachments.first.mime_type #=> 'application/pdf'@mail.attachments.first.decoded =='path/to/myfile.pdf') #=> true

You can also override the guessed MIME media type if you really know betterthan mail (this should be rarely needed)

ruby@mail =['myfile.pdf'] = { :mime_type => 'application/x-pdf', :content =>'path/to/myfile.pdf') } #=> 'application/x-pdf'

Of course… Mail will round trip an attachment as well

“`ruby@mail = do to ‘’ from ‘Mikel Lindsaar‘ subject ‘First multipart email sent with Mail’

text_part do body ‘Here is the attachment you wanted’ end

htmlpart do contenttype ‘text/html; charset=UTF-8’ body ‘

Funky Title

Here is the attachment you wanted

‘ end

add_file ‘/path/to/myfile.pdf’end

@roundtrippedmail =

@roundtrippedmail.attachments.length #=> 1@roundtrippedmail.attachments.first.filename #=> ‘myfile.pdf’“`See “Testing and extracting attachments” above for more details.

Using Mail with Testing or Spec’ing Libraries

If mail is part of your system, you’ll need a way to test it without actuallysending emails, the TestMailer can do this for you.

rubyrequire 'mail'=> trueMail.defaults do delivery_method :testend=> #Mail::TestMailer.deliveries=> []Mail.deliver do to '' from '' subject 'testing' body 'hello'end=> # 1Mail::TestMailer.deliveries.first=> # []

There is also a set of RSpec matchers stolen/inspired by Shoulda’s ActionMailer matchers (you’ll want to set delivery_method as above too):

“`rubyMail.defaults do deliverymethod :test # in practice you’d do this in spechelper.rbend

describe “sending an email” do include Mail::Matchers

before(:each) do Mail::TestMailer.deliveries.clear

Mail.deliver do  to ['', '']  from ''  subject 'testing'  body 'hello'end


it { havesent_email } # passes if any email at all was sent

it { havesentemail.from(‘’) } it {‘’) }

# can specify a list of recipients… it {[‘’, ‘’]) }

# …or chain recipients together it {‘’).to(‘’) }

it { havesentemail.withsubject(‘testing’) }

it { havesentemail.withbody(‘hello’) }

# Can match subject or body with a regex # (or anything that responds_to? :match)

it { havesentemail.matchingsubject(/test(ing)?/) } it { havesentemail.matchingbody(/h(a|e)llo/) }

# Can chain together modifiers # Note that apart from recipients, repeating a modifier overwrites old value.

it { havesentemail.from(‘’).to(‘’).matchingbody(/hell/)

# test for attachments

# … by specific attachment it { havesentemail.withattachments(my_attachment) }

# … or any attachment it { havesentemail.withattachments(any_attachment) }

# … by array of attachments it { havesentemail.withattachments([myattachment1, myattachment2]) } #note that order is important

#… by presence it { havesentemail.withany_attachments }

#… or by absence it { havesentemail.withno_attachments }


Excerpts from TREC Spam Corpus 2005

The spec fixture files in spec/fixtures/emails/fromtrec2005 are from the2005 TREC Public Spam Corpus. They remain copyrighted under the terms ofthat project and license agreement. They are used in this project to verifyand describe the development of this email parser implementation.

They are used as allowed by ‘Permitted Uses, Clause 3’:

"Small excerpts of the information may be displayed to others or published in a scientific or technical context, solely for the purpose of describing the research and development and related issues." --


(The MIT License)

Copyright (c) 2009-2016 Mikel Lindsaar

Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the’Software’), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:

The above copyright notice and this permission notice shall beincluded in all copies or substantial portions of the Software.


To restore the repository download the bundle


and run:

 git clone mikel-mail_-_2019-11-12_23-04-29.bundle 

Uploader: mikel
Upload date: 2019-11-12