{"id":13462990,"url":"https://github.com/mikel/mail","last_synced_at":"2025-05-12T13:00:29.933Z","repository":{"id":422647,"uuid":"79352","full_name":"mikel/mail","owner":"mikel","description":"A Really Ruby Mail Library","archived":false,"fork":false,"pushed_at":"2025-03-20T05:39:25.000Z","size":7089,"stargazers_count":3636,"open_issues_count":173,"forks_count":937,"subscribers_count":75,"default_branch":"master","last_synced_at":"2025-05-01T00:51:26.677Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mikel.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.rdoc","contributing":"CONTRIBUTING.md","funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2008-11-22T03:16:54.000Z","updated_at":"2025-04-29T19:18:10.000Z","dependencies_parsed_at":"2023-07-05T14:52:59.676Z","dependency_job_id":"fab87c8c-8f2f-4cc4-a7c7-1c65f94aeabe","html_url":"https://github.com/mikel/mail","commit_stats":{"total_commits":1669,"total_committers":278,"mean_commits":6.003597122302159,"dds":0.7435590173756741,"last_synced_commit":"73db11a6463ec330a36d68cfb77ef99511126cb0"},"previous_names":[],"tags_count":70,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikel%2Fmail","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikel%2Fmail/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikel%2Fmail/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikel%2Fmail/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mikel","download_url":"https://codeload.github.com/mikel/mail/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251840614,"owners_count":21652393,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T13:00:43.524Z","updated_at":"2025-05-03T02:32:59.988Z","avatar_url":"https://github.com/mikel.png","language":"Ruby","readme":"# Mail [![Build Status](https://github.com/mikel/mail/actions/workflows/test.yml/badge.svg)](https://github.com/mikel/mail/actions/workflows/test.yml)\n\n## Introduction\n\nMail is an internet library for Ruby that is designed to handle email\ngeneration, parsing and sending in a simple, rubyesque manner.\n\nThe purpose of this library is to provide a single point of access to handle\nall email functions, including sending and receiving email.  All network\ntype actions are done through proxy methods to Net::SMTP, Net::POP3 etc.\n\nBuilt from my experience with TMail, it is designed to be a pure ruby\nimplementation that makes generating, sending and parsing email a no\nbrainer.\n\nIt is also designed from the ground up to work with the more modern versions\nof Ruby.  Modern Rubies handle text encodings much more wonderfully than before\nso these features have been taken full advantage of in this library allowing\nMail to handle a lot more messages more cleanly than TMail.\n\nFinally, Mail has been designed with a very simple object oriented system\nthat really opens up the email messages you are parsing, if you know what\nyou are doing, you can fiddle with every last bit of your email directly.\n\n## You can contribute to this library\n\nYes, you! Mail is used in countless apps by people around the world. It is,\nlike all open source software, a labour of love borne from our free time.\nIf you would like to say thanks, please dig in and contribute alongside us!\nTriage and fix [GitHub issues](https://github.com/mikel/mail/issues), improve\nour documentation, add new features—up to you! Thank you for pitching in.\n\n\n# Contents\n* [Compatibility](#compatibility)\n* [Discussion](#discussion)\n* [Current Capabilities of Mail](#current-capabilities-of-mail)\n* [Roadmap](#roadmap)\n* [Testing Policy](#testing-policy)\n* [API Policy](#api-policy)\n* [Installation](#installation)\n* [Encodings](#encodings)\n* [Contributing](#contributing)\n* [Usage](#usage)\n* [Excerpts from TREC Spam Corpus 2005](#excerpts-from-trec-spam-corpus-2005)\n* [License](#license)\n\n## Compatibility\n\nMail is tested against:\n\n* Ruby: 2.5\n* Ruby: 2.6\n* Ruby: 2.7\n* Ruby: 3.0\n* Ruby: 3.1\n* Ruby: 3.2\n* JRuby: 9.2\n* JRuby: 9.3\n* JRuby: 9.4\n* JRuby: stable\n* JRuby: head\n* Truffleruby: stable\n* Truffleruby: head\n\nAs new versions of Ruby are released, Mail will be compatible with support for the \"preview\" and all \"normal maintenance\", \"security maintenance\" and the two most recent \"end of life\" versions listed at the [Ruby Maintenance Branches](https://www.ruby-lang.org/en/downloads/branches/) page.  Pull requests to assist in adding support for new preview releases are more than welcome.\n\nEvery Mail commit is tested by GitHub Actions on [all supported Ruby versions](https://github.com/mikel/mail/blob/master/.github/workflows/test.yml).\n\n## Discussion\n\nIf you want to discuss mail with like minded individuals, please subscribe to\nthe [Google Group](http://groups.google.com/group/mail-ruby).\n\n## Current Capabilities of Mail\n\n* RFC5322 Support, Reading and Writing\n* RFC6532 Support, reading UTF-8 headers\n* RFC2045-2049 Support for multipart email\n* Support for creating multipart alternate email\n* Support for reading multipart/report email \u0026amp; getting details from such\n* Wrappers for File, Net/POP3, Net/SMTP\n* Auto-encoding of non-US-ASCII bodies and header fields\n\nMail is RFC5322 and RFC6532 compliant now, that is, it can parse US-ASCII and UTF-8\nemail and generate US-ASCII email. There are a few obsoleted email syntax that\nit will have problems with, but it also is quite robust, meaning, if it finds something\nit doesn't understand it will not crash, instead, it will skip the problem and keep\nparsing. In the case of a header it doesn't understand, it will initialise the header\nas an optional unstructured field and continue parsing.\n\nThis means Mail won't (ever) crunch your data (I think).\n\nYou can also create MIME emails.  There are helper methods for making a\nmultipart/alternate email for text/plain and text/html (the most common pair)\nand you can manually create any other type of MIME email.\n\n## Roadmap\n\nNext TODO:\n\n* Improve MIME support for character sets in headers, currently works, mostly, needs\n  refinement.\n\n## Testing Policy\n\nBasically... we do BDD on Mail.  No method gets written in Mail without a\ncorresponding or covering spec.  We expect as a minimum 100% coverage\nmeasured by RCov.  While this is not perfect by any measure, it is pretty\ngood.  Additionally, all functional tests from TMail are to be passing before\nthe gem gets released.\n\nIt also means you can be sure Mail will behave correctly.\n\nYou can run tests locally by running `bundle exec rspec`.\n\nYou can run tests on all supported Ruby versions by using [act](https://github.com/nektos/act).\n\n## API Policy\n\nNo API removals within a single point release.  All removals to be deprecated with\nwarnings for at least one MINOR point release before removal.\n\nAlso, all private or protected methods to be declared as such - though this is still I/P.\n\n## Installation\n\nInstallation is fairly simple, I host mail on rubygems, so you can just do:\n\n    # gem install mail\n\n## Encodings\n\nIf you didn't know, handling encodings in Emails is not as straight forward as you\nwould hope.\n\nI have tried to simplify it some:\n\n1. All objects that can render into an email, have an `#encoded` method.  Encoded will\n   return the object as a complete string ready to send in the mail system, that is,\n   it will include the header field and value and CRLF at the end and wrapped as\n   needed.\n\n2. All objects that can render into an email, have a `#decoded` method.  Decoded will\n   return the object's \"value\" only as a string.  This means it will not include\n   the header fields (like 'To:' or 'Subject:').\n\n3. By default, calling \u003ccode\u003e#to_s\u003c/code\u003e on a container object will call its encoded\n   method, while \u003ccode\u003e#to_s\u003c/code\u003e on a field object will call its decoded method.\n   So calling \u003ccode\u003e#to_s\u003c/code\u003e on a Mail object will return the mail, all encoded\n   ready to send, while calling \u003ccode\u003e#to_s\u003c/code\u003e on the From field or the body will\n   return the decoded value of the object. The header object of Mail is considered a\n   container. If you are in doubt, call \u003ccode\u003e#encoded\u003c/code\u003e, or \u003ccode\u003e#decoded\u003c/code\u003e\n   explicitly, this is safer if you are not sure.\n\n4. Structured fields that have parameter values that can be encoded (e.g. Content-Type) will\n   provide decoded parameter values when you call the parameter names as methods against\n   the object.\n\n5. Structured fields that have parameter values that can be encoded (e.g. Content-Type) will\n   provide encoded parameter values when you call the parameter names through the\n   \u003ccode\u003eobject.parameters['\u003cparameter_name\u003e']\u003c/code\u003e method call.\n\n## Contributing\n\nPlease do!  Contributing is easy in Mail.  Please read the [CONTRIBUTING.md](CONTRIBUTING.md) document for more info.\n\n## Usage\n\nAll major mail functions should be able to happen from the Mail module.\nSo, you should be able to just \u003ccode\u003erequire 'mail'\u003c/code\u003e to get started.\n\n`mail` is pretty well documented in its Ruby code.  You can look it up e.g. at [rubydoc.info](https://www.rubydoc.info/gems/mail).\n\n### Making an email\n\n```ruby\nmail = Mail.new do\n  from    'mikel@test.lindsaar.net'\n  to      'you@test.lindsaar.net'\n  subject 'This is a test email'\n  body    File.read('body.txt')\nend\n\nmail.to_s #=\u003e \"From: mikel@test.lindsaar.net\\r\\nTo: you@...\n```\n\n### Making an email, have it your way:\n\n```ruby\nmail = Mail.new do\n  body File.read('body.txt')\nend\n\nmail['from'] = 'mikel@test.lindsaar.net'\nmail[:to]    = 'you@test.lindsaar.net'\nmail.subject = 'This is a test email'\n\nmail.header['X-Custom-Header'] = 'custom value'\n\nmail.to_s #=\u003e \"From: mikel@test.lindsaar.net\\r\\nTo: you@...\n```\n\n### Don't Worry About Message IDs:\n\n```ruby\nmail = Mail.new do\n  to   'you@test.lindsaar.net'\n  body 'Some simple body'\nend\n\nmail.to_s =~ /Message\\-ID: \u003c[\\d\\w_]+@.+.mail/ #=\u003e 27\n```\n\nMail will automatically add a Message-ID field if it is missing and\ngive it a unique, random Message-ID along the lines of:\n\n    \u003c4a7ff76d7016_13a81ab802e1@local.host.mail\u003e\n\n### Or do worry about Message-IDs:\n\n```ruby\nmail = Mail.new do\n  to         'you@test.lindsaar.net'\n  message_id '\u003cThisIsMyMessageId@some.domain.com\u003e'\n  body       'Some simple body'\nend\n\nmail.to_s =~ /Message\\-ID: \u003cThisIsMyMessageId@some.domain.com\u003e/ #=\u003e 27\n```\n\nMail will take the message_id you assign to it trusting that you know\nwhat you are doing.\n\n### Sending an email:\n\nMail defaults to sending via SMTP to local host port 25.  If you have a\nsendmail or postfix daemon running on this port, sending email is as\neasy as:\n\n```ruby\nMail.deliver do\n  from     'me@test.lindsaar.net'\n  to       'you@test.lindsaar.net'\n  subject  'Here is the image you wanted'\n  body     File.read('body.txt')\n  add_file '/full/path/to/somefile.png'\nend\n```\n\nor\n\n```ruby\nmail = Mail.new do\n  from     'me@test.lindsaar.net'\n  to       'you@test.lindsaar.net'\n  subject  'Here is the image you wanted'\n  body     File.read('body.txt')\n  add_file :filename =\u003e 'somefile.png', :content =\u003e File.read('/somefile.png')\nend\n\nmail.deliver!\n```\n\nSending via sendmail can be done like so:\n\n```ruby\nmail = Mail.new do\n  from     'me@test.lindsaar.net'\n  to       'you@test.lindsaar.net'\n  subject  'Here is the image you wanted'\n  body     File.read('body.txt')\n  add_file :filename =\u003e 'somefile.png', :content =\u003e File.read('/somefile.png')\nend\n\nmail.delivery_method :sendmail\n\nmail.deliver\n```\n\nSending via smtp (for example to [mailcatcher](https://github.com/sj26/mailcatcher))\n```ruby\n\nMail.defaults do\n  delivery_method :smtp, address: \"localhost\", port: 1025\nend\n```\n\n\nExim requires its own delivery manager, and can be used like so:\n\n```ruby\nmail.delivery_method :exim, :location =\u003e \"/usr/bin/exim\"\n\nmail.deliver\n```\n\nMail may be \"delivered\" to a logfile, too, for development and testing:\n\n```ruby\n# Delivers by logging the encoded message to $stdout\nmail.delivery_method :logger\n\n# Delivers to an existing logger at :debug severity\nmail.delivery_method :logger, logger: other_logger, severity: :debug\n```\n\n### Getting Emails from a POP or IMAP Server:\n\nYou can configure Mail to receive email using \u003ccode\u003eretriever_method\u003c/code\u003e\nwithin \u003ccode\u003eMail.defaults\u003c/code\u003e:\n\n```ruby\n# e.g. POP3\nMail.defaults do\n  retriever_method :pop3, :address    =\u003e \"pop.gmail.com\",\n                          :port       =\u003e 995,\n                          :user_name  =\u003e '\u003cusername\u003e',\n                          :password   =\u003e '\u003cpassword\u003e',\n                          :enable_ssl =\u003e true\nend\n\n# IMAP\nMail.defaults do\n  retriever_method :imap, :address    =\u003e \"imap.mailbox.org\",\n                          :port       =\u003e 993,\n                          :user_name  =\u003e '\u003cusername\u003e',\n                          :password   =\u003e '\u003cpassword\u003e',\n                          :enable_ssl =\u003e true\nend\n```\n\nYou can access incoming email in a number of ways.\n\nThe most recent email:\n\n```ruby\nMail.all    #=\u003e Returns an array of all emails\nMail.first  #=\u003e Returns the first unread email\nMail.last   #=\u003e Returns the last unread email\n```\n\nThe first 10 emails sorted by date in ascending order:\n\n```ruby\nemails = Mail.find(:what =\u003e :first, :count =\u003e 10, :order =\u003e :asc)\nemails.length #=\u003e 10\n```\n\nOr even all emails:\n\n```ruby\nemails = Mail.all\nemails.length #=\u003e LOTS!\n```\n\n\n### Reading an Email\n\n```ruby\nmail = Mail.read('/path/to/message.eml')\n\nmail.envelope_from   #=\u003e 'mikel@test.lindsaar.net'\nmail.from.addresses  #=\u003e ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']\nmail.sender.address  #=\u003e 'mikel@test.lindsaar.net'\nmail.to              #=\u003e 'bob@test.lindsaar.net'\nmail.cc              #=\u003e 'sam@test.lindsaar.net'\nmail.subject         #=\u003e \"This is the subject\"\nmail.date.to_s       #=\u003e '21 Nov 1997 09:55:06 -0600'\nmail.message_id      #=\u003e '\u003c4D6AA7EB.6490534@xxx.xxx\u003e'\nmail.decoded         #=\u003e 'This is the body of the email...\n```\n\nMany more methods available.\n\n### Reading a Multipart Email\n\n```ruby\nmail = Mail.read('multipart_email')\n\nmail.multipart?          #=\u003e true\nmail.parts.length        #=\u003e 2\nmail.body.preamble       #=\u003e \"Text before the first part\"\nmail.body.epilogue       #=\u003e \"Text after the last part\"\nmail.parts.map { |p| p.content_type }  #=\u003e ['text/plain', 'application/pdf']\nmail.parts.map { |p| p.class }         #=\u003e [Mail::Message, Mail::Message]\nmail.parts[0].content_type_parameters  #=\u003e {'charset' =\u003e 'ISO-8859-1'}\nmail.parts[1].content_type_parameters  #=\u003e {'name' =\u003e 'my.pdf'}\n```\n\nMail generates a tree of parts.  Each message has many or no parts.  Each part\nis another message which can have many or no parts.\n\nA message will only have parts if it is a multipart/mixed or multipart/related\ncontent type and has a boundary defined.\n\n### Testing and Extracting Attachments\n```ruby\nmail.attachments.each do | attachment |\n  # Attachments is an AttachmentsList object containing a\n  # number of Part objects\n  if (attachment.content_type.start_with?('image/'))\n    # extracting images for example...\n    filename = attachment.filename\n    begin\n      File.open(images_dir + filename, \"w+b\", 0644) {|f| f.write attachment.decoded}\n    rescue =\u003e e\n      puts \"Unable to save data for #{filename} because #{e.message}\"\n    end\n  end\nend\n```\n### Writing and Sending a Multipart/Alternative (HTML and Text) Email\n\nMail makes some basic assumptions and makes doing the common thing as\nsimple as possible.... (asking a lot from a mail library)\n\n```ruby\nmail = Mail.deliver do\n  part :content_type =\u003e \"multipart/mixed\" do |p1|\n    p1.part :content_type =\u003e \"multipart/related\" do |p2|\n      p2.part :content_type =\u003e \"multipart/alternative\",\n              :content_disposition =\u003e \"inline\" do |p3|\n        p3.part :content_type =\u003e \"text/plain; charset=utf-8\",\n                :body =\u003e \"Here is the attachment you wanted\\n\"\n        p3.part :content_type =\u003e \"text/html; charset=utf-8\",\n                :body =\u003e \"\u003ch1\u003eFunky Title\u003c/h1\u003e\u003cp\u003eHere is the attachment you wanted\u003c/p\u003e\\n\"\n      end\n    end\n    add_file '/path/to/myfile.pdf'\n  end\n  from      \"Mikel Lindsaar \u003cmikel@test.lindsaar.net.au\u003e\"\n  to        \"nicolas@test.lindsaar.net.au\"\n  subject   \"First multipart email sent with Mail\"\nend\n```\n\nMail then delivers the email at the end of the block and returns the\nresulting Mail::Message object, which you can then inspect if you\nso desire...\n\n```\nputs mail.to_s #=\u003e\n\nDate: Tue, 26 Apr 2022 20:12:07 +0200\nFrom: Mikel Lindsaar \u003cmikel@test.lindsaar.net.au\u003e\nTo: nicolas@test.lindsaar.net.au\nMessage-ID: \u003c626835f736e19_10873fdfa3c2ffd4947a3@sender.at.mail\u003e\nSubject: First multipart email sent with Mail\nMIME-Version: 1.0\nContent-Type: multipart/mixed;\n boundary=\\\"--==_mimepart_626835f733867_10873fdfa3c2ffd494636\\\";\n charset=UTF-8\nContent-Transfer-Encoding: 7bit\n\n\n----==_mimepart_626835f733867_10873fdfa3c2ffd494636\nContent-Type: multipart/mixed;\n boundary=\\\"--==_mimepart_626835f73382a_10873fdfa3c2ffd494518\\\";\n charset=UTF-8\nContent-Transfer-Encoding: 7bit\n\n\n----==_mimepart_626835f73382a_10873fdfa3c2ffd494518\nContent-Type: multipart/related;\n boundary=\\\"--==_mimepart_626835f7337f5_10873fdfa3c2ffd494438\\\";\n charset=UTF-8\nContent-Transfer-Encoding: 7bit\n\n\n----==_mimepart_626835f7337f5_10873fdfa3c2ffd494438\nContent-Type: multipart/alternative;\n boundary=\\\"--==_mimepart_626835f733702_10873fdfa3c2ffd494376\\\";\n charset=UTF-8\nContent-Transfer-Encoding: 7bit\nContent-Disposition: inline\nContent-ID: \u003c626835f738373_10873fdfa3c2ffd49488b@sender.at.mail\u003e\n\n\n----==_mimepart_626835f733702_10873fdfa3c2ffd494376\nContent-Type: text/plain;\n charset=utf-8\nContent-Transfer-Encoding: 7bit\n\nHere is the attachment you wanted\n\n----==_mimepart_626835f733702_10873fdfa3c2ffd494376\nContent-Type: text/html;\n charset=utf-8\nContent-Transfer-Encoding: 7bit\n\n\u003ch1\u003eFunky Title\u003c/h1\u003e\u003cp\u003eHere is the attachment you wanted\u003c/p\u003e\n\n----==_mimepart_626835f733702_10873fdfa3c2ffd494376--\n\n----==_mimepart_626835f7337f5_10873fdfa3c2ffd494438--\n\n----==_mimepart_626835f73382a_10873fdfa3c2ffd494518--\n\n----==_mimepart_626835f733867_10873fdfa3c2ffd494636\nContent-Type: text/plain;\n charset=UTF-8;\n filename=myfile.txt\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment;\n filename=myfile.txt\nContent-ID: \u003c6\n26835f7386ab_10873fdfa3c2ffd4949b8@sender.at.mail\u003e\n\nHallo,\nTest\nEnd\n\n----==_mimepart_626835f733867_10873fdfa3c2ffd494636--\n```\n\nMail inserts the content transfer encoding, the mime version,\nthe content-IDs and handles the content-type and boundary.\n\nMail assumes that if your text in the body is only us-ascii, that your\ntransfer encoding is 7bit and it is text/plain.  You can override this\nby explicitly declaring it.\n\n### Making Multipart/Alternate, Without a Block\n\nYou don't have to use a block with the text and html part included, you\ncan just do it declaratively.  However, you need to add Mail::Parts to\nan email, not Mail::Messages.\n\n```ruby\nmail = Mail.new do\n  to      'nicolas@test.lindsaar.net.au'\n  from    'Mikel Lindsaar \u003cmikel@test.lindsaar.net.au\u003e'\n  subject 'First multipart email sent with Mail'\nend\n\ntext_part = Mail::Part.new do\n  body 'This is plain text'\nend\n\nhtml_part = Mail::Part.new do\n  content_type 'text/html; charset=UTF-8'\n  body '\u003ch1\u003eThis is HTML\u003c/h1\u003e'\nend\n\nmail.text_part = text_part\nmail.html_part = html_part\n```\n\nResults in the same email as done using the block form\n\n### Getting Error Reports from an Email:\n\n```ruby\n@mail = Mail.read('/path/to/bounce_message.eml')\n\n@mail.bounced?         #=\u003e true\n@mail.final_recipient  #=\u003e rfc822;mikel@dont.exist.com\n@mail.action           #=\u003e failed\n@mail.error_status     #=\u003e 5.5.0\n@mail.diagnostic_code  #=\u003e smtp;550 Requested action not taken: mailbox unavailable\n@mail.retryable?       #=\u003e false\n```\n\n### Attaching and Detaching Files\n\nYou can just read the file off an absolute path, Mail will try\nto guess the mime_type and will encode the file in Base64 for you.\n\n```ruby\n@mail = Mail.new\n@mail.add_file(\"/path/to/file.jpg\")\n@mail.parts.first.attachment? #=\u003e true\n@mail.parts.first.content_transfer_encoding.to_s #=\u003e 'base64'\n@mail.attachments.first.mime_type #=\u003e 'image/jpg'\n@mail.attachments.first.filename #=\u003e 'file.jpg'\n@mail.attachments.first.decoded == File.read('/path/to/file.jpg') #=\u003e true\n```\n\nOr You can pass in file_data and give it a filename, again, mail\nwill try and guess the mime_type for you.\n\n```ruby\n@mail = Mail.new\n@mail.attachments['myfile.pdf'] = File.read('path/to/myfile.pdf')\n@mail.parts.first.attachment? #=\u003e true\n@mail.attachments.first.mime_type #=\u003e 'application/pdf'\n@mail.attachments.first.decoded == File.read('path/to/myfile.pdf') #=\u003e true\n```\n\nYou can also override the guessed MIME media type if you really know better\nthan mail (this should be rarely needed)\n\n```ruby\n@mail = Mail.new\n@mail.attachments['myfile.pdf'] = { :mime_type =\u003e 'application/x-pdf',\n                                    :content =\u003e File.read('path/to/myfile.pdf') }\n@mail.parts.first.mime_type #=\u003e 'application/x-pdf'\n```\n\nOf course... Mail will round trip an attachment as well\n\n```ruby\n@mail = Mail.new do\n  to      'nicolas@test.lindsaar.net.au'\n  from    'Mikel Lindsaar \u003cmikel@test.lindsaar.net.au\u003e'\n  subject 'First multipart email sent with Mail'\n\n  text_part do\n    body 'Here is the attachment you wanted'\n  end\n\n  html_part do\n    content_type 'text/html; charset=UTF-8'\n    body '\u003ch1\u003eFunky Title\u003c/h1\u003e\u003cp\u003eHere is the attachment you wanted\u003c/p\u003e'\n  end\n\n  add_file '/path/to/myfile.pdf'\nend\n\n@round_tripped_mail = Mail.new(@mail.encoded)\n\n@round_tripped_mail.attachments.length #=\u003e 1\n@round_tripped_mail.attachments.first.filename #=\u003e 'myfile.pdf'\n```\nSee \"Testing and extracting attachments\" above for more details.\n\n## Using Mail with Testing or Spec'ing Libraries\n\nIf mail is part of your system, you'll need a way to test it without actually\nsending emails, the TestMailer can do this for you.\n\n```ruby\nrequire 'mail'\n=\u003e true\nMail.defaults do\n  delivery_method :test\nend\n=\u003e #\u003cMail::Configuration:0x19345a8 @delivery_method=Mail::TestMailer\u003e\nMail::TestMailer.deliveries\n=\u003e []\nMail.deliver do\n  to 'mikel@me.com'\n  from 'you@you.com'\n  subject 'testing'\n  body 'hello'\nend\n=\u003e #\u003cMail::Message:0x19284ec ...\nMail::TestMailer.deliveries.length\n=\u003e 1\nMail::TestMailer.deliveries.first\n=\u003e #\u003cMail::Message:0x19284ec ...\nMail::TestMailer.deliveries.clear\n=\u003e []\n```\n\nThere is also a set of RSpec matchers stolen/inspired by Shoulda's ActionMailer matchers (you'll want to set \u003ccode\u003edelivery_method\u003c/code\u003e as above too):\n\n```ruby\nMail.defaults do\n  delivery_method :test # in practice you'd do this in spec_helper.rb\nend\n\nRSpec.describe \"sending an email\" do\n  include Mail::Matchers\n\n  before(:each) do\n    Mail::TestMailer.deliveries.clear\n\n    Mail.deliver do\n      to ['mikel@me.com', 'mike2@me.com']\n      from 'you@you.com'\n      subject 'testing'\n      body 'hello'\n    end\n  end\n\n  it { is_expected.to have_sent_email } # passes if any email at all was sent\n\n  it { is_expected.to have_sent_email.from('you@you.com') }\n  it { is_expected.to have_sent_email.to('mike1@me.com') }\n\n  # can specify a list of recipients...\n  it { is_expected.to have_sent_email.to(['mike1@me.com', 'mike2@me.com']) }\n\n  # ...or chain recipients together\n  it { is_expected.to have_sent_email.to('mike1@me.com').to('mike2@me.com') }\n\n  it { is_expected.to have_sent_email.with_subject('testing') }\n\n  it { is_expected.to have_sent_email.with_body('hello') }\n\n  # Can match subject or body with a regex\n  # (or anything that responds_to? :match)\n\n  it { is_expected.to have_sent_email.matching_subject(/test(ing)?/) }\n  it { is_expected.to have_sent_email.matching_body(/h(a|e)llo/) }\n\n  # Can chain together modifiers\n  # Note that apart from recipients, repeating a modifier overwrites old value.\n\n  it { is_expected.to have_sent_email.from('you@you.com').to('mike1@me.com').matching_body(/hell/)\n\n  # test for attachments\n\n  # ... by specific attachment\n  it { is_expected.to have_sent_email.with_attachments(my_attachment) }\n\n  # ... or any attachment\n  it { is_expected.to have_sent_email.with_attachments(any_attachment) }\n\n  # ... or attachment with filename\n  it { is_expected.to have_sent_email.with_attachments(an_attachment_with_filename('file.txt')) }\n\n  # ... or attachment with mime_type\n  it { is_expected.to have_sent_email.with_attachments(an_attachment_with_mime_type('application/pdf')) }\n\n  # ... by array of attachments\n  it { is_expected.to have_sent_email.with_attachments([my_attachment1, my_attachment2]) } #note that order is important\n\n  #... by presence\n  it { is_expected.to have_sent_email.with_any_attachments }\n\n  #... or by absence\n  it { is_expected.to have_sent_email.with_no_attachments }\n\nend\n```\n\n## Excerpts from TREC Spam Corpus 2005\n\nThe spec fixture files in spec/fixtures/emails/from_trec_2005 are from the\n2005 TREC Public Spam Corpus. They remain copyrighted under the terms of\nthat project and license agreement. They are used in this project to verify\nand describe the development of this email parser implementation.\n\nhttp://plg.uwaterloo.ca/~gvcormac/treccorpus/\n\nThey are used as allowed by 'Permitted Uses, Clause 3':\n\n    \"Small excerpts of the information may be displayed to others\n     or published in a scientific or technical context, solely for\n     the purpose of describing the research and development and\n     related issues.\"\n\n     -- http://plg.uwaterloo.ca/~gvcormac/treccorpus/\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2009-2016 Mikel Lindsaar\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","funding_links":[],"categories":["Communication","Ruby","Web 后端","Email","E-Mail","Gems"],"sub_categories":["E-Mail Sending","Mail"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmikel%2Fmail","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmikel%2Fmail","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmikel%2Fmail/lists"}