github.com-mikel-mail_-_2019-11-12_23-04-29

github.com-mikel-mail_-_2019-11-12_23-04-29

Posted by

Download
ITEM TILE – File Size: 10.2K

A Really Ruby Mail Library

Mail Build Status

Introduction

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.

Contents

Compatibility

Mail supports Ruby 1.8.7+, including JRuby and Rubinius.

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

Discussion

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.

Roadmap

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

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

# gem install mail

Encodings

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.

Contributing

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

Usage

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 = Mail.new do from ‘mikel@test.lindsaar.net’ to ‘you@test.lindsaar.net’ subject ‘This is a test email’ body File.read(‘body.txt’)end

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

Making an email, have it your way:

“`rubymail = Mail.new do body File.read(‘body.txt’)end

mail[‘from’] = ‘mikel@test.lindsaar.net’mail[:to] = ‘you@test.lindsaar.net’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 = Mail.new do to ‘you@test.lindsaar.net’ 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 = Mail.new do to ‘you@test.lindsaar.net’ message_id ‘ThisIsMyMessageId@some.domain.com‘ body ‘Some simple body’end

mail.to_s =~ /Message-ID: ThisIsMyMessageId@some.domain.com/ #=> 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 'me@test.lindsaar.net' to 'you@test.lindsaar.net' subject 'Here is the image you wanted' body File.read('body.txt') add_file '/full/path/to/somefile.png'end

or

“`rubymail = Mail.new do from ‘me@test.lindsaar.net’ to ‘you@test.lindsaar.net’ subject ‘Here is the image you wanted’ body File.read(‘body.txt’) add_file :filename => ‘somefile.png’, :content => File.read(‘/somefile.png’)end

mail.deliver!“`

Sending via sendmail can be done like so:

“`rubymail = Mail.new do from ‘me@test.lindsaar.net’ to ‘you@test.lindsaar.net’ subject ‘Here is the image you wanted’ body File.read(‘body.txt’) add_file :filename => ‘somefile.png’, :content => File.read(‘/somefile.png’)end

mail.delivery_method :sendmail

mail.deliver“`

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.deliver“`

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

“`ruby

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 => "pop.gmail.com", :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 = Mail.read(‘/path/to/message.eml’)

mail.envelopefrom #=> ‘mikel@test.lindsaar.net’mail.from.addresses #=> [‘mikel@test.lindsaar.net’, ‘ada@test.lindsaar.net’]mail.sender.address #=> ‘mikel@test.lindsaar.net’mail.to #=> ‘bob@test.lindsaar.net’mail.cc #=> ‘sam@test.lindsaar.net’mail.subject #=> “This is the subject”mail.date.tos #=> ’21 Nov 1997 09:55:06 -0600’mail.message_id #=> ‘4D6AA7EB.6490534@xxx.xxx‘mail.decoded #=> ‘This is the body of the email…“`

Many more methods available.

Reading a Multipart Email

“`rubymail = Mail.read(‘multipart_email’)

mail.multipart? #=> truemail.parts.length #=> 2mail.body.preamble #=> “Text before the first part”mail.body.epilogue #=> “Text after the last part”mail.parts.map { |p| p.contenttype } #=> [‘text/plain’, ‘application/pdf’]mail.parts.map { |p| p.class } #=> [Mail::Message, Mail::Message]mail.parts[0].contenttypeparameters #=> {‘charset’ => ‘ISO-8859-1’}mail.parts[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 File.open(images_dir + 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 ‘nicolas@test.lindsaar.net.au’ from ‘Mikel Lindsaar mikel@test.lindsaar.net.au‘ 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: nicolas@test.lindsaar.net.auFrom: Mikel Lindsaar mikel@test.lindsaar.net.auSubject: 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

—-==mimepart4a914f0c911be_6f0f1ab8026659–“`

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 = Mail.new do to ‘nicolas@test.lindsaar.net.au’ from ‘Mikel Lindsaar mikel@test.lindsaar.net.au‘ subject ‘First multipart email sent with Mail’end

text_part = Mail::Part.new do body ‘This is plain text’end

htmlpart = Mail::Part.new do contenttype ‘text/html; charset=UTF-8’ body ‘

This is HTML

‘end

mail.textpart = textpartmail.htmlpart = htmlpart“`

Results in the same email as done using the block form

Getting Error Reports from an Email:

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

@mail.bounced? #=> true@mail.finalrecipient #=> rfc822;mikel@dont.exist.com@mail.action #=> 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 = Mail.new@mail.add_file("/path/to/file.jpg")@mail.parts.first.attachment? #=> true@mail.parts.first.content_transfer_encoding.to_s #=> 'base64'@mail.attachments.first.mime_type #=> 'image/jpg'@mail.attachments.first.filename #=> 'file.jpg'@mail.attachments.first.decoded == File.read('/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 = Mail.new@mail.attachments['myfile.pdf'] = File.read('path/to/myfile.pdf')@mail.parts.first.attachment? #=> true@mail.attachments.first.mime_type #=> 'application/pdf'@mail.attachments.first.decoded == File.read('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 = Mail.new@mail.attachments['myfile.pdf'] = { :mime_type => 'application/x-pdf', :content => File.read('path/to/myfile.pdf') }@mail.parts.first.mime_type #=> 'application/x-pdf'

Of course… Mail will round trip an attachment as well

“`ruby@mail = Mail.new do to ‘nicolas@test.lindsaar.net.au’ from ‘Mikel Lindsaar mikel@test.lindsaar.net.au‘ 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 = Mail.new(@mail.encoded)

@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 'mikel@me.com' from 'you@you.com' 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 ['mikel@me.com', 'mike2@me.com']  from 'you@you.com'  subject 'testing'  body 'hello'end

end

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

it { isexpected.to havesentemail.from(‘you@you.com’) } it { isexpected.to havesentemail.to(‘mike1@me.com’) }

# can specify a list of recipients… it { isexpected.to havesent_email.to([‘mike1@me.com’, ‘mike2@me.com’]) }

# …or chain recipients together it { isexpected.to havesent_email.to(‘mike1@me.com’).to(‘mike2@me.com’) }

it { isexpected.to havesentemail.withsubject(‘testing’) }

it { isexpected.to havesentemail.withbody(‘hello’) }

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

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

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

it { isexpected.to havesentemail.from(‘you@you.com’).to(‘mike1@me.com’).matchingbody(/hell/)

# test for attachments

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

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

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

#… by presence it { isexpected.to havesentemail.withany_attachments }

#… or by absence it { isexpected.to havesentemail.withno_attachments }

end“`

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.

http://plg.uwaterloo.ca/~gvcormac/treccorpus/

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." -- http://plg.uwaterloo.ca/~gvcormac/treccorpus/

License

(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.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANYCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

To restore the repository download the bundle

wget https://archive.org/download/github.com-mikel-mail_-_2019-11-12_23-04-29/mikel-mail_-_2019-11-12_23-04-29.bundle

and run:

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

Source: https://github.com/mikel/mail
Uploader: mikel
Upload date: 2019-11-12