Giter Site home page Giter Site logo

mail's Introduction

Mail Build Status

Introduction

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

The purpose of this library is to provide a single point of access to handle all email functions, including sending and receiving email. All network type 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 ruby implementation that makes generating, sending and parsing email a no brainer.

It is also designed from the ground up to work with the more modern versions of Ruby. Modern Rubies handle text encodings much more wonderfully than before so these features have been taken full advantage of in this library allowing Mail to handle a lot more messages more cleanly than TMail.

Finally, Mail has been designed with a very simple object oriented system that really opens up the email messages you are parsing, if you know what you 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, improve our documentation, add new features—up to you! Thank you for pitching in.

Contents

Compatibility

Mail is tested against:

  • Ruby: 2.5
  • Ruby: 2.6
  • Ruby: 2.7
  • Ruby: 3.0
  • Ruby: 3.1
  • Ruby: 3.2
  • JRuby: 9.2
  • JRuby: 9.3
  • JRuby: 9.4
  • JRuby: stable
  • JRuby: head
  • Truffleruby: stable
  • Truffleruby: head

As 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 page. Pull requests to assist in adding support for new preview releases are more than welcome.

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

Discussion

If you want to discuss mail with like minded individuals, please subscribe to the 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-8 email and generate US-ASCII email. There are a few obsoleted email syntax that it will have problems with, but it also is quite robust, meaning, if it finds something it doesn't understand it will not crash, instead, it will skip the problem and keep parsing. In the case of a header it doesn't understand, it will initialise the header as 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 a multipart/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, needs refinement.

Testing Policy

Basically... we do BDD on Mail. No method gets written in Mail without a corresponding or covering spec. We expect as a minimum 100% coverage measured by RCov. While this is not perfect by any measure, it is pretty good. Additionally, all functional tests from TMail are to be passing before the gem gets released.

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

You can run tests locally by running bundle exec rspec.

You can run tests on all supported Ruby versions by using act.

API Policy

No API removals within a single point release. All removals to be deprecated with warnings 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 you would hope.

I have tried to simplify it some:

  1. All objects that can render into an email, have an #encoded method. Encoded will return 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 as needed.

  2. All objects that can render into an email, have a #decoded method. Decoded will return the object's "value" only as a string. This means it will not include the header fields (like 'To:' or 'Subject:').

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

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

  5. Structured fields that have parameter values that can be encoded (e.g. Content-Type) will provide encoded parameter values when you call the parameter names through the object.parameters['<parameter_name>'] 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.

mail is pretty well documented in its Ruby code. You can look it up e.g. at rubydoc.info.

Making an email

mail = Mail.new do
  from    '[email protected]'
  to      '[email protected]'
  subject 'This is a test email'
  body    File.read('body.txt')
end

mail.to_s #=> "From: [email protected]\r\nTo: you@...

Making an email, have it your way:

mail = Mail.new do
  body File.read('body.txt')
end

mail['from'] = '[email protected]'
mail[:to]    = '[email protected]'
mail.subject = 'This is a test email'

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

mail.to_s #=> "From: [email protected]\r\nTo: you@...

Don't Worry About Message IDs:

mail = Mail.new do
  to   '[email protected]'
  body 'Some simple body'
end

mail.to_s =~ /Message\-ID: <[\d\w_]+@.+.mail/ #=> 27

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

Or do worry about Message-IDs:

mail = Mail.new do
  to         '[email protected]'
  message_id '<[email protected]>'
  body       'Some simple body'
end

mail.to_s =~ /Message\-ID: <[email protected]>/ #=> 27

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

Sending an email:

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

Mail.deliver do
  from     '[email protected]'
  to       '[email protected]'
  subject  'Here is the image you wanted'
  body     File.read('body.txt')
  add_file '/full/path/to/somefile.png'
end

or

mail = Mail.new do
  from     '[email protected]'
  to       '[email protected]'
  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:

mail = Mail.new do
  from     '[email protected]'
  to       '[email protected]'
  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)

Mail.defaults do
  delivery_method :smtp, address: "localhost", port: 1025
end

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

mail.delivery_method :exim, :location => "/usr/bin/exim"

mail.deliver

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.delivery_method :logger, logger: other_logger, severity: :debug

Getting Emails from a POP or IMAP Server:

You can configure Mail to receive email using retriever_method within Mail.defaults:

# e.g. POP3
Mail.defaults do
  retriever_method :pop3, :address    => "pop.gmail.com",
                          :port       => 995,
                          :user_name  => '<username>',
                          :password   => '<password>',
                          :enable_ssl => true
end

# IMAP
Mail.defaults do
  retriever_method :imap, :address    => "imap.mailbox.org",
                          :port       => 993,
                          :user_name  => '<username>',
                          :password   => '<password>',
                          :enable_ssl => true
end

You can access incoming email in a number of ways.

The most recent email:

Mail.all    #=> Returns an array of all emails
Mail.first  #=> Returns the first unread email
Mail.last   #=> Returns the last unread email

The first 10 emails sorted by date in ascending order:

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

Or even all emails:

emails = Mail.all
emails.length #=> LOTS!

Reading an Email

mail = Mail.read('/path/to/message.eml')

mail.envelope_from   #=> '[email protected]'
mail.from.addresses  #=> ['[email protected]', '[email protected]']
mail.sender.address  #=> '[email protected]'
mail.to              #=> '[email protected]'
mail.cc              #=> '[email protected]'
mail.subject         #=> "This is the subject"
mail.date.to_s       #=> '21 Nov 1997 09:55:06 -0600'
mail.message_id      #=> '<[email protected]>'
mail.decoded         #=> 'This is the body of the email...

Many more methods available.

Reading a Multipart Email

mail = Mail.read('multipart_email')

mail.multipart?          #=> true
mail.parts.length        #=> 2
mail.body.preamble       #=> "Text before the first part"
mail.body.epilogue       #=> "Text after the last part"
mail.parts.map { |p| p.content_type }  #=> ['text/plain', 'application/pdf']
mail.parts.map { |p| p.class }         #=> [Mail::Message, Mail::Message]
mail.parts[0].content_type_parameters  #=> {'charset' => 'ISO-8859-1'}
mail.parts[1].content_type_parameters  #=> {'name' => 'my.pdf'}

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

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

Testing and Extracting Attachments

mail.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
  end
end

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

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

mail = Mail.deliver do
  part :content_type => "multipart/mixed" do |p1|
    p1.part :content_type => "multipart/related" do |p2|
      p2.part :content_type => "multipart/alternative",
              :content_disposition => "inline" do |p3|
        p3.part :content_type => "text/plain; charset=utf-8",
                :body => "Here is the attachment you wanted\n"
        p3.part :content_type => "text/html; charset=utf-8",
                :body => "<h1>Funky Title</h1><p>Here is the attachment you wanted</p>\n"
      end
    end
    add_file '/path/to/myfile.pdf'
  end
  from      "Mikel Lindsaar <[email protected]>"
  to        "[email protected]"
  subject   "First multipart email sent with Mail"
end

Mail then delivers the email at the end of the block and returns the resulting Mail::Message object, which you can then inspect if you so desire...

puts mail.to_s #=>

Date: Tue, 26 Apr 2022 20:12:07 +0200
From: Mikel Lindsaar <[email protected]>
To: [email protected]
Message-ID: <[email protected]>
Subject: First multipart email sent with Mail
MIME-Version: 1.0
Content-Type: multipart/mixed;
 boundary=\"--==_mimepart_626835f733867_10873fdfa3c2ffd494636\";
 charset=UTF-8
Content-Transfer-Encoding: 7bit


----==_mimepart_626835f733867_10873fdfa3c2ffd494636
Content-Type: multipart/mixed;
 boundary=\"--==_mimepart_626835f73382a_10873fdfa3c2ffd494518\";
 charset=UTF-8
Content-Transfer-Encoding: 7bit


----==_mimepart_626835f73382a_10873fdfa3c2ffd494518
Content-Type: multipart/related;
 boundary=\"--==_mimepart_626835f7337f5_10873fdfa3c2ffd494438\";
 charset=UTF-8
Content-Transfer-Encoding: 7bit


----==_mimepart_626835f7337f5_10873fdfa3c2ffd494438
Content-Type: multipart/alternative;
 boundary=\"--==_mimepart_626835f733702_10873fdfa3c2ffd494376\";
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
Content-ID: <[email protected]>


----==_mimepart_626835f733702_10873fdfa3c2ffd494376
Content-Type: text/plain;
 charset=utf-8
Content-Transfer-Encoding: 7bit

Here is the attachment you wanted

----==_mimepart_626835f733702_10873fdfa3c2ffd494376
Content-Type: text/html;
 charset=utf-8
Content-Transfer-Encoding: 7bit

<h1>Funky Title</h1><p>Here is the attachment you wanted</p>

----==_mimepart_626835f733702_10873fdfa3c2ffd494376--

----==_mimepart_626835f7337f5_10873fdfa3c2ffd494438--

----==_mimepart_626835f73382a_10873fdfa3c2ffd494518--

----==_mimepart_626835f733867_10873fdfa3c2ffd494636
Content-Type: text/plain;
 charset=UTF-8;
 filename=myfile.txt
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
 filename=myfile.txt
Content-ID: <6
[email protected]>

Hallo,
Test
End

----==_mimepart_626835f733867_10873fdfa3c2ffd494636--

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 your transfer encoding is 7bit and it is text/plain. You can override this by explicitly declaring it.

Making Multipart/Alternate, Without a Block

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

mail = Mail.new do
  to      '[email protected]'
  from    'Mikel Lindsaar <[email protected]>'
  subject 'First multipart email sent with Mail'
end

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

html_part = Mail::Part.new do
  content_type 'text/html; charset=UTF-8'
  body '<h1>This is HTML</h1>'
end

mail.text_part = text_part
mail.html_part = html_part

Results in the same email as done using the block form

Getting Error Reports from an Email:

@mail = Mail.read('/path/to/bounce_message.eml')

@mail.bounced?         #=> true
@mail.final_recipient  #=> rfc822;[email protected]
@mail.action           #=> failed
@mail.error_status     #=> 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 try to guess the mime_type and will encode the file in Base64 for you.

@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 file_data and give it a filename, again, mail will try and guess the mime_type for you.

@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 better than mail (this should be rarely needed)

@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

@mail = Mail.new do
  to      '[email protected]'
  from    'Mikel Lindsaar <[email protected]>'
  subject 'First multipart email sent with Mail'

  text_part do
    body 'Here is the attachment you wanted'
  end

  html_part do
    content_type 'text/html; charset=UTF-8'
    body '<h1>Funky Title</h1><p>Here is the attachment you wanted</p>'
  end

  add_file '/path/to/myfile.pdf'
end

@round_tripped_mail = Mail.new(@mail.encoded)

@round_tripped_mail.attachments.length #=> 1
@round_tripped_mail.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 actually sending emails, the TestMailer can do this for you.

require 'mail'
=> true
Mail.defaults do
  delivery_method :test
end
=> #<Mail::Configuration:0x19345a8 @delivery_method=Mail::TestMailer>
Mail::TestMailer.deliveries
=> []
Mail.deliver do
  to '[email protected]'
  from '[email protected]'
  subject 'testing'
  body 'hello'
end
=> #<Mail::Message:0x19284ec ...
Mail::TestMailer.deliveries.length
=> 1
Mail::TestMailer.deliveries.first
=> #<Mail::Message:0x19284ec ...
Mail::TestMailer.deliveries.clear
=> []

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):

Mail.defaults do
  delivery_method :test # in practice you'd do this in spec_helper.rb
end

RSpec.describe "sending an email" do
  include Mail::Matchers

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

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

  it { is_expected.to have_sent_email } # passes if any email at all was sent

  it { is_expected.to have_sent_email.from('[email protected]') }
  it { is_expected.to have_sent_email.to('[email protected]') }

  # can specify a list of recipients...
  it { is_expected.to have_sent_email.to(['[email protected]', '[email protected]']) }

  # ...or chain recipients together
  it { is_expected.to have_sent_email.to('[email protected]').to('[email protected]') }

  it { is_expected.to have_sent_email.with_subject('testing') }

  it { is_expected.to have_sent_email.with_body('hello') }

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

  it { is_expected.to have_sent_email.matching_subject(/test(ing)?/) }
  it { is_expected.to have_sent_email.matching_body(/h(a|e)llo/) }

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

  it { is_expected.to have_sent_email.from('[email protected]').to('[email protected]').matching_body(/hell/)

  # test for attachments

  # ... by specific attachment
  it { is_expected.to have_sent_email.with_attachments(my_attachment) }

  # ... or any attachment
  it { is_expected.to have_sent_email.with_attachments(any_attachment) }

  # ... or attachment with filename
  it { is_expected.to have_sent_email.with_attachments(an_attachment_with_filename('file.txt')) }

  # ... or attachment with mime_type
  it { is_expected.to have_sent_email.with_attachments(an_attachment_with_mime_type('application/pdf')) }

  # ... by array of attachments
  it { is_expected.to have_sent_email.with_attachments([my_attachment1, my_attachment2]) } #note that order is important

  #... by presence
  it { is_expected.to have_sent_email.with_any_attachments }

  #... or by absence
  it { is_expected.to have_sent_email.with_no_attachments }

end

Excerpts from TREC Spam Corpus 2005

The spec fixture files in spec/fixtures/emails/from_trec_2005 are from the 2005 TREC Public Spam Corpus. They remain copyrighted under the terms of that project and license agreement. They are used in this project to verify and 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 obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included 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 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mail's People

Contributors

ahorek avatar amatsuda avatar arunagw avatar benabik avatar bf4 avatar bogdan avatar bpot avatar c960657 avatar calvincorreli avatar conradirwin avatar dasch avatar dball avatar deivid-rodriguez avatar eval avatar fasta avatar grosser avatar jeremy avatar jeremyevans avatar jlindley avatar kennyj avatar kjg avatar lewispb avatar mikel avatar olleolleolle avatar pzb avatar sebbasf avatar srawlins avatar ultraninja avatar yalab avatar zettabyte avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mail's Issues

Problem parsing mail

Using Email gem mail 2.1.2, I have problems parsing a mail with "From" in the body and some dots in a concrete order. If I change the "From" for a "from" it works. Here an example (first one fails, second one works):

require 'rubygems'
require 'mail'
mail = Mail.new("Subject: Welcome\nFrom: Test <[email protected]>\nTo: [email protected]\nContent-Type: text/plain\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\n\nFrom .\n.\n\n")
puts mail.subject
mail2 = Mail.new("Subject: Welcome\nFrom: Test <[email protected]>\nTo: [email protected]\nContent-Type: text/plain\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\n\nfrom .\n.\n\n")
puts mail2.subject

the output is:

$ irb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'mail'
=> true
irb(main):003:0> mail = Mail.new("Subject: Welcome\nFrom: Test <[email protected]>\nTo: [email protected]\nContent-Type: text/plain\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\n\nFrom .\n.\n\n")
=> #<Mail::Message:0x7f14ab81fd00 @raw_envelope=".", @perform_deliveries=true, @delivery_notification_observers=[], @html_part=nil, @delivery_handler=nil, @raw_source=".", @text_part=nil, @header=#<Mail::Header:0x7f14ab81f120 @fields=[#<Mail::Field:0x7f14ab81edb0 @field=#<Mail::OptionalField:0x7f14ab81ed10 @value=nil, @length=nil, @element=nil, @name=".", @tree=nil>>], @raw_source=".", @unfolded_header=".">, @envelope=#<Mail::Envelope:0x7f14ab81f3f0 @value=".", @length=nil, @element=nil, @name=/[!-9;-~]+/, @tree=nil>, @delivery_method=#<Mail::SMTP:0x7f14ab81fc38 @settings={:user_name=>nil, :enable_starttls_auto=>true, :authentication=>nil, :address=>"localhost", :password=>nil, :port=>25, :domain=>"localhost.localdomain"}>, @raise_delivery_errors=true, @body=#<Mail::Body:0x7f14ab81ee50 @charset="US-ASCII", @preamble=nil, @boundary=nil, @encoding=nil, @parts=[], @part_sort_order=["text/plain", "text/enriched", "text/html"], @raw_source="", @epilogue=nil>>
irb(main):004:0> puts mail.subject
nil
=> nil
irb(main):005:0> mail2 = Mail.new("Subject: Welcome\nFrom: Test <[email protected]>\nTo: [email protected]\nContent-Type: text/plain\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\n\nfrom .\n.\n\n")
=> #<Mail::Message:0x7f14ab809230 @perform_deliveries=true, @delivery_notification_observers=[], @html_part=nil, @delivery_handler=nil, @raw_source="Subject: Welcome\r\nFrom: Test <[email protected]>\r\nTo: [email protected]\r\nContent-Type: text/plain\r\nMime-Version: 1.0\r\nContent-Transfer-Encoding: 7bit\r\n\r\nfrom .\r\n.", @text_part=nil, @header=#<Mail::Header:0x7f14ab808998 @fields=[#<Mail::Field:0x7f14ab808178 @field=#<Mail::FromField:0x7f14ab807a48 @value="Test <[email protected]>", @length=nil, @element=nil, @name="From", @tree=#<Mail::AddressList:0x7f14ab8078e0 @address_nodes=[SyntaxNode+Address1+NameAddr0 offset=0, "Test <[email protected]>" (angle_addr,comments,display_name,dig_comments):
  SyntaxNode offset=0, "Test ":
    SyntaxNode+Atom0 offset=0, "Test ":
      SyntaxNode+CFWS1 offset=0, "":
    SyntaxNode offset=0, ""
    SyntaxNode offset=0, ""
      SyntaxNode offset=0, "Test":
    SyntaxNode offset=0, "T"
    SyntaxNode offset=1, "e"
    SyntaxNode offset=2, "s"
    SyntaxNode offset=3, "t"
      SyntaxNode+CFWS1 offset=4, " ":
    SyntaxNode offset=4, ""
    SyntaxNode+ObsFWS1 offset=4, " ":
      SyntaxNode offset=4, " ":
        SyntaxNode offset=4, " "
      SyntaxNode offset=5, ""
  SyntaxNode+AngleAddr0 offset=5, "<[email protected]>" (addr_spec):
    SyntaxNode+CFWS1 offset=5, "":
      SyntaxNode offset=5, ""
      SyntaxNode offset=5, ""
    SyntaxNode offset=5, "<"
    SyntaxNode+AddrSpec0 offset=6, "[email protected]" (domain,local_part):
      SyntaxNode+LocalDotAtom0 offset=6, "test" (local_dot_atom_text):
    SyntaxNode+CFWS1 offset=6, "":
      SyntaxNode offset=6, ""
      SyntaxNode offset=6, ""
    SyntaxNode offset=6, "test":
      SyntaxNode+LocalDotAtomText0 offset=6, "test" (domain_text):
        SyntaxNode offset=6, ""
        SyntaxNode offset=6, "test":
          SyntaxNode offset=6, "t"
          SyntaxNode offset=7, "e"
          SyntaxNode offset=8, "s"
          SyntaxNode offset=9, "t"
    SyntaxNode+CFWS1 offset=10, "":
      SyntaxNode offset=10, ""
      SyntaxNode offset=10, ""
      SyntaxNode offset=10, "@"
      SyntaxNode+DotAtom0 offset=11, "test.com" (dot_atom_text):
    SyntaxNode+CFWS1 offset=11, "":
      SyntaxNode offset=11, ""
      SyntaxNode offset=11, ""
    SyntaxNode offset=11, "test.com":
      SyntaxNode+DotAtomText0 offset=11, "test." (domain_text):
        SyntaxNode offset=11, "test":
          SyntaxNode offset=11, "t"
          SyntaxNode offset=12, "e"
          SyntaxNode offset=13, "s"
          SyntaxNode offset=14, "t"
        SyntaxNode offset=15, "."
      SyntaxNode+DotAtomText0 offset=16, "com" (domain_text):
        SyntaxNode offset=16, "com":
          SyntaxNode offset=16, "c"
          SyntaxNode offset=17, "o"
          SyntaxNode offset=18, "m"
        SyntaxNode offset=19, ""
    SyntaxNode+CFWS1 offset=19, "":
      SyntaxNode offset=19, ""
      SyntaxNode offset=19, ""
    SyntaxNode offset=19, ">"
    SyntaxNode+CFWS1 offset=20, "":
      SyntaxNode offset=20, ""
      SyntaxNode offset=20, ""]>>>, #<Mail::Field:0x7f14ab7fb270 @field=#<Mail::ToField:0x7f14ab7faf78 @value="[email protected]", @length=nil, @element=nil, @name="To", @tree=#<Mail::AddressList:0x7f14ab7fae10 @address_nodes=[SyntaxNode+Address1+AddrSpec0 offset=0, "[email protected]" (comments,domain,local_part,dig_comments):
  SyntaxNode+LocalDotAtom0 offset=0, "test" (local_dot_atom_text):
    SyntaxNode+CFWS1 offset=0, "":
      SyntaxNode offset=0, ""
      SyntaxNode offset=0, ""
    SyntaxNode offset=0, "test":
      SyntaxNode+LocalDotAtomText0 offset=0, "test" (domain_text):
    SyntaxNode offset=0, ""
    SyntaxNode offset=0, "test":
      SyntaxNode offset=0, "t"
      SyntaxNode offset=1, "e"
      SyntaxNode offset=2, "s"
      SyntaxNode offset=3, "t"
    SyntaxNode+CFWS1 offset=4, "":
      SyntaxNode offset=4, ""
      SyntaxNode offset=4, ""
  SyntaxNode offset=4, "@"
  SyntaxNode+DotAtom0 offset=5, "test.com" (dot_atom_text):
    SyntaxNode+CFWS1 offset=5, "":
      SyntaxNode offset=5, ""
      SyntaxNode offset=5, ""
    SyntaxNode offset=5, "test.com":
      SyntaxNode+DotAtomText0 offset=5, "test." (domain_text):
    SyntaxNode offset=5, "test":
      SyntaxNode offset=5, "t"
      SyntaxNode offset=6, "e"
      SyntaxNode offset=7, "s"
      SyntaxNode offset=8, "t"
    SyntaxNode offset=9, "."
      SyntaxNode+DotAtomText0 offset=10, "com" (domain_text):
    SyntaxNode offset=10, "com":
      SyntaxNode offset=10, "c"
      SyntaxNode offset=11, "o"
      SyntaxNode offset=12, "m"
    SyntaxNode offset=13, ""
    SyntaxNode+CFWS1 offset=13, "":
      SyntaxNode offset=13, ""
      SyntaxNode offset=13, ""]>>>, #<Mail::Field:0x7f14ab808128 @field=#<Mail::SubjectField:0x7f14ab807e58 @value="Welcome", @length=nil, @element=nil, @name="Subject", @tree=nil>>, #<Mail::Field:0x7f14ab7ee6b0 @field=#<Mail::MimeVersionField:0x7f14ab7ee368 @value="1.0", @length=nil, @element=#<Mail::MimeVersionElement:0x7f14ab7ee1b0 @minor="0", @major="1">, @name="Mime-Version", @tree=nil>>, #<Mail::Field:0x7f14ab7f1dd8 @field=#<Mail::ContentTypeField:0x7f14ab7f1a90 @parameters=nil, @value="text/plain", @length=nil, @element=#<Mail::ContentTypeElement:0x7f14ab7f18b0 @parameters=[], @main_type="text", @sub_type="plain">, @main_type="text", @name="Content-Type", @tree=nil, @sub_type=nil>>, #<Mail::Field:0x7f14ab7ead30 @field=#<Mail::ContentTransferEncodingField:0x7f14ab7ea9c0 @value="7bit", @length=nil, @element=nil, @name="Content-Transfer-Encoding", @tree=nil>>], @raw_source="Subject: Welcome\r\nFrom: Test <[email protected]>\r\nTo: [email protected]\r\nContent-Type: text/plain\r\nMime-Version: 1.0\r\nContent-Transfer-Encoding: 7bit", @unfolded_header="Subject: Welcome\r\nFrom: Test <[email protected]>\r\nTo: [email protected]\r\nContent-Type: text/plain\r\nMime-Version: 1.0\r\nContent-Transfer-Encoding: 7bit">, @delivery_method=#<Mail::SMTP:0x7f14ab8091b8 @settings={:user_name=>nil, :enable_starttls_auto=>true, :authentication=>nil, :address=>"localhost", :password=>nil, :port=>25, :domain=>"localhost.localdomain"}>, @raise_delivery_errors=true, @body=#<Mail::Body:0x7f14ab7eada8 @charset="US-ASCII", @preamble=nil, @boundary=nil, @encoding="7bit", @parts=[], @part_sort_order=["text/plain", "text/enriched", "text/html"], @raw_source="from .\r\n.", @epilogue=nil>>
irb(main):006:0> puts mail2.subject
Welcome
=> nil
irb(main):007:0>

Wrong subject field folding

Please have a look at the subject field:

Subject: =?utf-8?Q?=D0=92=D0=BE=D1=81=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=B[NEW_LINE_HERE]
    B=D0=B5=D0=BD=D0=B8=D0=B5_=D0=92=D0=B0=D1=88=D0=B5=D0=B3=D0=BE_=D0=BF=D0=B0=D1[NEW_LINE_HERE]
    =80=D0=BE=D0=BB=D1=8F?=

So my Thunderbird and Gmail cant correctly display subject of the mail.

spec failure related to date/time offset

Getting a failure where the only diff is the offset of two times being compared.

$ spec ./spec/mail/fields/resent_date_field_spec.rb:43 -cfn
Running Specs under Ruby Version 1.8.7
Mail::ResentDateField
  should give today's date if no date is specified (FAILED - 1)

1)
'Mail::ResentDateField should give today's date if no date is specified' FAILED
expected: Sun, 21 Feb 2010 12:10:23 -0600,
     got: Sun, 21 Feb 2010 12:10:23 -0500 (using ==)
./spec/mail/fields/resent_date_field_spec.rb:43:

Finished in 0.019357 seconds

1 example, 1 failure

Error Installing mail gem.

gem install mail
Successfully installed mail-2.1.2
1 gem installed
Installing ri documentation for mail-2.1.2...
ERROR: While executing gem ... (NoMethodError)
undefined method `empty?' for nil:NilClass

Not sure what that nil class is, please check. Thanks.

from address with display name

Hi. I am trying to use the mail gem to parse an rfc822 but I am having some difficulty navigating the attributes. For example, I would like to get an array of email address with their corresponding display names for all of the address fields. Looks like the from attributes return a simple array with just the address.

m = Mail.read('features/fixtures/email_fixtures/mail_552')

m.from
=> ["[email protected]"]

m.from_addrs
=> ["[email protected]"]

It looks like Mail comes with an Address class but I am not sure how to leverage it.

thx.

-karl

Adding several To addresses not possible?

Hi,

I've been trying add to several to addresses to an outgoing e-mail.
Reading Mail::Message:to (and to=) documentation I found nothing about several recipients.

I tried to add several recipents by:
mail = Mail.new do
to '[email protected]'
to '[email protected]'
...
end
puts mail
Which just sets the to field to the second address. Then I tested adding them as an array into to but then I got an error about gsub on an array.

I ended up doing
mail = Mail.new do
self['To'] = '[email protected], [email protected]'
....
end
puts mail

Which set To to both addresses and the mail was delivered successfully to all recipients.

Is this the intended way of doing this or am I missing something obious? :)

/ba

Updating 'from' does not work

I tried to extend Mail::Message to provide a default 'from' address by wrapping the old initialize with my own which would first call the old initialize, then set defaults, then instance_eval if a block was specified, and finally return self. All seemed to go well until I tried to override from= inside the block. This resulted in a message that, when delivered, raised this error:

NoMethodError: undefined method `addresses' for #<Mail::OptionalField:0xb72ab068>
    from /home/ben/.gem/ruby/1.8/gems/mail-1.3.0/lib/mail/field.rb:120:in `send'
    from /home/ben/.gem/ruby/1.8/gems/mail-1.3.0/lib/mail/field.rb:120:in `method_missing'
    from /home/ben/.gem/ruby/1.8/gems/mail-1.3.0/lib/mail/network/delivery_methods/smtp.rb:60:in `deliver!'
    from /home/ben/.gem/ruby/1.8/gems/mail-1.3.0/lib/mail/network/deliverable.rb:11:in `perform_delivery!'
    from /home/ben/.gem/ruby/1.8/gems/mail-1.3.0/lib/mail/message.rb:68:in `deliver!'
    from (irb):20
    from /home/ben/.gem/ruby/1.8/gems/treetop-1.4.2/lib/treetop/compiler/metagrammar.rb:415

First, I thought the problem might be that I now had multiple 'from' addresses and went to RFC 822 to see if that even made sense. Indeed, multiple authorship is valid, provided a single 'Sender' is specified, but when I inspected the message in irb, I did not find that multiple authorship had been set. Instead, I noticed something very odd about the message that results from trying to call 'from' twice, and that is that FromField is removed and replaced with an OptionalField with @name==:from (I have thrown some debug print statements in to see when we're doing an 'update' vs. 'create'):

>> mail.from='[email protected]'
[:create, "from", "[email protected]"]
=> "[email protected]"
>> mail.inspect
=> "#<Mail::Message:0xb72aff64 @header=#<Mail::Header:0xb72afd84 @fields=[#<Mail::Field:0xb72ade80 @field=#<Mail::FromField:0xb72addf4 @length=nil, @element=nil, @tree=nil, @value=\"[email protected]\", @name=\"From\">>], @raw_source=\"\">, @raw_source=\"\", @body=#<Mail::Body:0xb72afd5c @charset=\"US-ASCII\", @encoding=nil, @raw_source=\"\">>"
>> mail.from='[email protected]'
[:update, "from", "[email protected]"]
=> "[email protected]"
>> mail.inspect
=> "#<Mail::Message:0xb72aff64 @header=#<Mail::Header:0xb72afd84 @fields=[#<Mail::Field:0xb72ade80 @field=#<Mail::OptionalField:0xb72ab068 @length=nil, @element=nil, @tree=nil, @value=\"[email protected]\", @name=:from>>], @raw_source=\"\">, @raw_source=\"\", @body=#<Mail::Body:0xb72afd5c @charset=\"US-ASCII\", @encoding=nil, @raw_source=\"\">>"

Of course, to work around this problem, I could make users delete from after establishing the default to set a new value, but that's not very friendly, e.g.

>> mail=Mail.new
...
>> mail.from.value
"[email protected]"
>> mail.from nil
...
>> mail.from "[email protected]"

Ideally, what I would like mail.from= to do is to replace the old from address with the new. But failing that, I would like some way to specify a default 'from' address to use that, if no from address was specified by the time the message is delivered, would be used.

Duplicate block call in configuration.rb

mail/configuration.rb line 98 following, change from:

def set_settings(klass, host_array = nil, &block)
  if host_array
    klass.instance.settings do
      host host_array[0]
      port host_array[1]
    end
  end
  if block_given?
    klass.instance.settings(&block)
  end
  klass.instance.settings(&block)
end

To:
def set_settings(klass, host_array = nil, &block)
if host_array
klass.instance.settings do
host host_array[0]
port host_array[1]
end
end
klass.instance.settings(&block) if block_given?
end

Bad content-types

What is the proper way to handle bad content types? I've read about as many RFC's today as I can stand, and I missed the content-type fall back recommendations if they're in there.

Of 400mb or so of email I've attempted to parse today (largely the Enron mail corpus) the vast majority of parse errors were on the content-type header.

Mostly things like

Content-Type: text

(Instead of text/plain)

Or like:

Content-Type: multipart/mixed boundary="----=_NextPart_000_000F_01C17754.8C3CAF30"

(Missing the ';' delimiter before the value hash)

I committed a fix to my fork[1] that sets content-type to 'text/plain' on parser errors, but that doesn't feel quite right. Should it just ignore that field in the header altogether?

Thanks-

Jim

[1] http://github.com/jlindley/mail/commit/2fd51a8d757bbec2a7ef553b6bc52486b45539ab

Doesn't Work with Gmail SMTP

EDIT, again

Actually does this lib work with gmail's smtp? I am a bit confused.

EDIT

This issue was already opened before. My bad -- I didn't see the list of issues before opening a new one. Please delete this one.

I get the following error if I try to use Gmail's SMTP server.
SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I found this on searching: http://www.ruby-forum.com/topic/176626
and I think you need to add http.verify_mode = OpenSSL::SSL::VERIFY_NONE somewhere. I don't know where though. :(

Hope I have provided enough information regarding the issue. Also I've enable tls so that wasn't the problem.

Crash when parsing mail with 2.1.5.3

The following test program crashes with Ruby 1.9 and 1.8. The test case may be a bit weired, but I see this problem with lots of real-world mails.

require 'rubygems'
require 'mail'

Mail.new <<'EOT'
Date: Wed, 03 Mar 2010 09:50:41 +0100
From: [email protected]
To: [email protected]
Message-ID: <1234foo.mail>
Subject: This mail crashes ruby-mail
Content-Type: plain/text; charset=UTF-8
Content-Transfer-Encoding: 8bit

Hello Sébastien Bono!

EOT

Ruby 1.9.x:

/usr/local/lib/ruby/gems/1.9.1/gems/mail-2.1.5.3/lib/mail/core_extensions/string.rb:4:in gsub': invalid byte sequence in US-ASCII (ArgumentError) from /usr/local/lib/ruby/gems/1.9.1/gems/mail-2.1.5.3/lib/mail/core_extensions/string.rb:4:into_crlf'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-2.1.5.3/lib/mail/message.rb:1737:in raw_source=' from /usr/local/lib/ruby/gems/1.9.1/gems/mail-2.1.5.3/lib/mail/message.rb:1825:ininit_with_string'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-2.1.5.3/lib/mail/message.rb:116:in initialize' from /usr/local/lib/ruby/gems/1.9.1/gems/mail-2.1.5.3/lib/mail/mail.rb:50:innew'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-2.1.5.3/lib/mail/mail.rb:50:in new' from mail-creation-bug.rb:4:in

'

Ruby 1.8:

/usr/lib64/ruby/gems/1.8/gems/mail-2.1.5.2/lib/mail/field.rb:122:in send': undefined methodmain_type' for #Mail::UnstructuredField:0x7f4d467b2ce0 (NoMethodError)
from /usr/lib64/ruby/gems/1.8/gems/mail-2.1.5.2/lib/mail/field.rb:122:in method_missing' from /usr/lib64/ruby/gems/1.8/gems/mail-2.1.5.2/lib/mail/message.rb:1392:inmain_type'
from /usr/lib64/ruby/gems/1.8/gems/mail-2.1.5.2/lib/mail/message.rb:1413:in multipart?' from /usr/lib64/ruby/gems/1.8/gems/mail-2.1.5.2/lib/mail/message.rb:1828:ininit_with_string'
from /usr/lib64/ruby/gems/1.8/gems/mail-2.1.5.2/lib/mail/message.rb:116:in initialize' from /usr/lib64/ruby/gems/1.8/gems/mail-2.1.5.2/lib/mail/mail.rb:50:innew'
from /usr/lib64/ruby/gems/1.8/gems/mail-2.1.5.2/lib/mail/mail.rb:50:in `new'
from mail-creation-bug.rb:4

Wrong comment

In the file /lib/mail/network/delivery_methods/smtp.rb on line 43 the comment is
Turn on TLS

but it should be
Turn off TLS

Warnings when running with warnings enabled

If I try to send a mail with ruby -w I get the following error:
mail-2.1.3/lib/mail/parts_list.rb:18: warning: discarding old collect

The mail gets sent and everything is working fine, but I'd rather not run with warnings disabled :)

ba@bamse: ~> ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]

/ba

Potential issue on Mail::Body#sort_parts! being trigger by internal api

Hi,

First of all congrats for this lib, the api and code is so much better than Tmail!

Just wanna share my feeling about an issue I got that confused me. It may or may not be an issue as I was just testing/playing with the api and not working on real world use case:

The use of Mail::Body#sort_parts! by Mail::Body#encoded implies unexpected side effects.
@mail.text_parts returns different result depending on the fact that sort has been done (this is true in case of multipart email containing multipart parts as sort_parts! wont sort Mail::Message#all_parts properly

This lead to first level text/plain part to become systematically Mail::Message.text_part after Mail::Body#encoded as been executed (before the execution this was the first text/plain part in the order or the mail even if this text/plain part was itself inside a multipart part).

IMHO there should be no #sort_parts! method changing @Parts instance variable. This sorting should be done dynamically during #encoded execution without altering @Parts instance variable, and thus without changing the behavior of some other methods in other instance. This is not limited to Mail::Message#text_part as it may change Mail::Message#html_part, it changes Mail::Message#parts and Mail::Message#all_parts too (Mail::Message#all_parts not beeing sorted the same way that Mail::Message#parts is).

Invalid byte sequence in UTF-8 on Mail.read

This library looks great but I'm having a problem opening up some .eml emails, I get this error:

mail = Mail.read("email.eml")
ArgumentError: invalid byte sequence in UTF-8
from /var/lib/gems/1.9.1/gems/mail-1.3.0/lib/mail/core_extensions/string.rb:4:in gsub' from /var/lib/gems/1.9.1/gems/mail-1.3.0/lib/mail/core_extensions/string.rb:4:into_crlf'
from /var/lib/gems/1.9.1/gems/mail-1.3.0/lib/mail/message.rb:100:in raw_source=' from /var/lib/gems/1.9.1/gems/mail-1.3.0/lib/mail/message.rb:896:ininit_with_string'
from /var/lib/gems/1.9.1/gems/mail-1.3.0/lib/mail/message.rb:57:in initialize' from /var/lib/gems/1.9.1/gems/mail-1.3.0/lib/mail/mail.rb:50:innew'
from /var/lib/gems/1.9.1/gems/mail-1.3.0/lib/mail/mail.rb:50:in new' from /var/lib/gems/1.9.1/gems/mail-1.3.0/lib/mail/mail.rb:139:inread'

Error in readme

The readme includes the following fragment that doesn't work in mail >= 2.0:

Mail.defaults do
smtp '127.0.0.1', 25
end

PDF-file with foreign characters will not send correctly

Can anyone manage to attach http://assets.io.no/file.pdf with mail? I've tried every option I can think of, and I've never managed to send an email successfully with the attachment attached (it just shows up as text in the email). Attaching it in OS X Mail etc works perfectly well.

The email from mail comes like this:
(But I have tried every kind of encoding etc, nothing has worked). I'm on ruby 1.9.1

Date: Sat, 16 Jan 2010 18:21:21 +0100
Mime-Version: 1.0
Content-Type: text/plain;
charset="UTF-8";
Content-Transfer-Encoding: 8bit
Content-ID: [email protected]

This is a test with foreign characters æ ø

Date: Sat, 16 Jan 2010 18:21:21 +0100
Mime-Version: 1.0
Content-Type: application/x-pdf;
boundary="--==_mimepart_4b51f5919693f_9a6f8043247074276";
charset="US-ASCII";
filename="file.pdf";
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="file.pdf"
Content-ID: [email protected]

JVBERi0xLjQKJeLjz9MKCjEgMCBvYmoKPDwvVHlwZSAvQ2F0YWxvZwovUGFn
ZXMgMiAwIFIKL1BhZ2VNb2RlIC9GdWxsU2NyZWVuPj4KZW5kb2JqCgoyIDAg
b2JqCjw8L1R5cGUgL1BhZ2VzCi9LaWRzIFszIDAgUl0KL0NvdW50IDE+Pgpl...

Certain header field names are all lower case

See custom header X-Foo-Bar and In-Reply-To below.

[xpc:0] tmp> gem19 list mail

*** LOCAL GEMS ***

mail (2.1.3)
[xpc:0] tmp> cat mail-header-bug.rb
#!/usr/bin/env ruby

require 'mail'

mail = Mail.new do
  from '[email protected]'
  to '[email protected]'
  subject 'This is a test email'
  in_reply_to 'id123'
  body 'Hello, world!'
end
mail['X-Foo-Bar'] = 'Some custom text'

puts mail.to_s
[xpc:0] tmp> ruby19 mail-header-bug.rb
Date: Tue, 16 Mar 2010 19:24:21 +0100
From: [email protected]
To: [email protected]
Message-ID: <[email protected]>
in-reply-to: id123
Subject: This is a test email
Mime-Version: 1.0
Content-Type: text/plain;
        charset="US-ASCII";
Content-Transfer-Encoding: 7bit
x-foo-bar: Some custom text

Hello, world!

Problem setting Return-Path

There seems to be a problem setting the Return-path as described here. The Return-path seems to be set, but not present when the mail gets delivered.

mail = Mail.new do
to "[email protected]"
from "[email protected]"
subject "Can't set the return-path"
#this seems to set the return-path prior to sending
self['return-path'] = "[email protected]"
message_id "#{mail_id}@someemail.com"
body "body"
end

here the Return Path seems to be set as "[email protected]"

mail.deliver!

when the email is received, the return path is set as

"[email protected]"

investigating two encoding spec failures in jruby

I cloned mail today and ran the specs in ruby 1.8.6 p369 on MacOS X 10.5.8, everything passed (what I expected).

Then I pulled the latest changes for jruby 1.5.0dev, built it and ran the specs: 1072 examples, 2 failures, 6 pending

spec/mail/encodings/encodings_spec.rb:492:

1)
'Mail::Encodings altering an encoded text to decoded and visa versa unquote and convert to should unquote a string in the middle of the text' FAILED
expected: "Re: Photos Broschüre Rand",
     got: "Re: Photos Broschüre_Rand" (using ==)

 Diff:
@@ -1,2 +1,2 @@
-Re: Photos Broschüre Rand
+Re: Photos Broschüre_Rand

spec/mail/encodings/encodings_spec.rb:500

2)
'Mail::Encodings altering an encoded text to decoded and visa versa unquote and convert to should unquote and change to an ISO encoding if we really want' FAILED
expected: "Broschüre Rand",
     got: "Broschüre_Rand" (using ==)

 Diff:
@@ -1,2 +1,2 @@
-Broschüre Rand
+Broschüre_Rand

JRuby didn't convert the '_' char into a space ...?

I don't understand yet why the fixtures have '_' chars and why these are turned into spaces ... but I see that pattern in many places and it's working in ruby and jruby fine almost everywhere.

This seemed pretty strange so I put a debugger statement in the class method: Encodings.unquote_and_convert_to at line 135 in encodings.rb and ran the spec tests in ruby and jruby.

 spec -u spec/mail/encodings/encodings_spec.rb

and
jruby -S spec -u spec/mail/encodings/encodings_spec.rb

FYI: in jruby 1.5 the debugger is included.

One strange difference I found is that in Ruby ActiveSupport::CoreExtensions::String::OutputSafety method: add_with_safety is somehow hooking itself into String#unpack. This doesn't happen in JRuby.

Here's the irb session from Ruby:

[12, 21] in /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings/quoted_printable.rb
   12          EightBit.can_encode? str
   13        end
   14  
   15        # Decode the string from Quoted-Printable
   16        def self.decode(str)
=> 17          str.unpack("M*").first
   18        end
   19  
   20        def self.encode(str)
   21          l = []
/Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings/quoted_printable.rb:17
str.unpack("M*").first
(rdb:1) w
--> #0 quoted-printable.decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings/quoted_printable.rb:17
    #1 Mail::Ruby18.[](str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/version_specific/ruby_1_8.rb:67
    #2 Mail::Encodings.q_value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:203
    #3 String.value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:124
    #4 Mail::Encodings.value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:116
    #5 Mail::Encodings.unquote_and_convert_to(str#String, to_encoding#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:136
    #6 at line spec/mail/encodings/encodings_spec.rb:491
    #7 Timeout.execute(sec#NilClass, klass#NilClass) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:40
    #8 Spec::Example::ExampleMethods.execute(run_options#Spec::Runner::Options, instance_variables#Hash,...) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:37
    #9 Spec::Example::ExampleGroupMethods.run_examples(success#TrueClass, instance_variables#Hash,...) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:214
Warning: saved frames may be incomplete; compare with caller(0).
(rdb:1) str
"Brosch=FCre_Rand"
(rdb:1) str.unpack("M*")
["Broschüre_Rand"]
(rdb:1) str.unpack("M*").first
"Broschüre_Rand"
(rdb:1) s
[64, 73] in /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/version_specific/ruby_1_8.rb
   64        match = str.match(/\=\?(.+)?\?[Qq]\?(.+)?\?\=/m)
   65        if match
   66          encoding = match[1]
   67          str = Encodings::QuotedPrintable.decode(match[2])
   68        end
=> 69        str
   70      end
   71      
   72      def Ruby18.param_decode(str, encoding)
   73        URI.unescape(str)
/Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/version_specific/ruby_1_8.rb:69
str
(rdb:1) str
"Broschüre_Rand"
(rdb:1) w
--> #0 Mail::Ruby18.q_value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/version_specific/ruby_1_8.rb:69
    #1 Mail::Encodings.q_value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:203
    #2 String.value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:124
    #3 Mail::Encodings.value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:116
    #4 Mail::Encodings.unquote_and_convert_to(str#String, to_encoding#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:136
    #5 at line spec/mail/encodings/encodings_spec.rb:491
    #6 Timeout.execute(sec#NilClass, klass#NilClass) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:40
    #7 Spec::Example::ExampleMethods.execute(run_options#Spec::Runner::Options, instance_variables#Hash,...) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:37
    #8 Spec::Example::ExampleGroupMethods.run_examples(success#TrueClass, instance_variables#Hash,...) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:214
Warning: saved frames may be incomplete; compare with caller(0).
(rdb:1) s
[20, 29] in /Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/string/output_safety.rb
   20            @_rails_html_safe = true
   21            self
   22          end
   23  
   24          def add_with_safety(other)
=> 25            result = add_without_safety(other)
   26            if html_safe? && also_html_safe?(other)
   27              result.html_safe!
   28            else
   29              result
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/string/output_safety.rb:25
result = add_without_safety(other)
(rdb:1) caller(0)
["/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/string/output_safety.rb:25:in `value_decode'", "/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/string/output_safety.rb:25:in `value_decode'", "/Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:116:in `gsub'", "/Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:116:in `value_decode'", "/Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:136:in `unquote_and_convert_to'", "./spec/mail/encodings/encodings_spec.rb:491", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:40:in `instance_eval'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:40:in `execute'", "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/timeout.rb:53:in `timeout'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:37:in `execute'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:214:in `run_examples'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:212:in `each'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:212:in `run_examples'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:103:in `run'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:23:in `run'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:22:in `each'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:22:in `run'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/options.rb:152:in `run_examples'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/command_line.rb:9:in `run'", "/Library/Ruby/Gems/1.8/gems/rspec-1.3.0/bin/spec:5", "/usr/bin/spec:19:in `load'", "/usr/bin/spec:19"]
(rdb:1) w
--> #0 ActiveSupport::CoreExtensions::String::OutputSafety.+(other#String) 
       at line /Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/string/output_safety.rb:25
    #1 String.value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:124
    #2 Mail::Encodings.value_decode(str#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:116
    #3 Mail::Encodings.unquote_and_convert_to(str#String, to_encoding#String) 
       at line /Users/stephen/dev/ruby/src/gems/mail-git/lib/mail/encodings.rb:136
    #4 at line spec/mail/encodings/encodings_spec.rb:491
    #5 Timeout.execute(sec#NilClass, klass#NilClass) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:40
    #6 Spec::Example::ExampleMethods.execute(run_options#Spec::Runner::Options, instance_variables#Hash,...) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_methods.rb:37
    #7 Spec::Example::ExampleGroupMethods.run_examples(success#TrueClass, instance_variables#Hash,...) 
       at line /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:214
Warning: saved frames may be incomplete; compare with caller(0).

followed by a similar session in JRuby (but no interaction with Active3Support)

[12, 21] in lib/mail/encodings/quoted_printable.rb
   12          EightBit.can_encode? str
   13        end
   14  
   15        # Decode the string from Quoted-Printable
   16        def self.decode(str)
=> 17          str.unpack("M*").first
   18        end
   19  
   20        def self.encode(str)
   21          l = []
lib/mail/encodings/quoted_printable.rb:17
str.unpack("M*").first
(rdb:1) str
"Brosch=FCre_Rand"
(rdb:1)  str.unpack("M*").first
"Broschüre_Rand"
(rdb:1) s
[64, 73] in lib/mail/version_specific/ruby_1_8.rb
   64        match = str.match(/\=\?(.+)?\?[Qq]\?(.+)?\?\=/m)
   65        if match
   66          encoding = match[1]
   67          str = Encodings::QuotedPrintable.decode(match[2])
   68        end
=> 69        str
   70      end
   71      
   72      def Ruby18.param_decode(str, encoding)
   73        URI.unescape(str)
lib/mail/version_specific/ruby_1_8.rb:69
str
(rdb:1) str
"Broschüre_Rand"
(rdb:1) s
[112, 121] in lib/mail/encodings.rb
   112      # 
   113      # String has to be of the format =?<encoding>?[QB]?<string>?=
   114      def Encodings.value_decode(str)
   115        str.gsub!(/\?=(\s*)=\?/, '?==?') # Remove whitespaces between 'encoded-word's
   116        str.gsub(/(.*?)(=\?.*?\?.\?.*?\?=)|$/m) do
=> 117          before = $1.to_s
   118          text = $2.to_s
   119          
   120          case
   121          when text =~ /=\?.+\?[Bb]\?/m
lib/mail/encodings.rb:117

Attachments don't show up on the other side

I'm trying to send an email with attachment from gmail to yahoo.
Mail puts:

...

   ----==_mimepart_4bac6ecf1625c_1fb5800b81ac18492
   Date: Fri, 26 Mar 2010 10:22:39 +0200
   Mime-Version: 1.0
   Content-Type: text/html;
   charset="UTF-8";
   Content-Transfer-Encoding: 7bit
   Content-ID: <[email protected]>

....

    ----==_mimepart_4bac6ecf1625c_1fb5800b81ac18492
   Date: Fri, 26 Mar 2010 10:22:39 +0200
   Mime-Version: 1.0
   Content-Type: application/msword;
   charset="US-ASCII";
   filename="somefile.doc";
  Content-Transfer-Encoding: base64
  Content-Disposition: attachment; filename="somefile.doc"
  Content-ID: <[email protected]>

...

So there is an attachment. When I try to read email on yahoo webmail, it shows mail size of 80kb, but no attachment enclosed.

What's wrong?

Thank you in advance

Ordering of add_file and body items causes invalid emails

If you're adding a file attachment to an email and you don't specify the body before the add file command the mail doesn't generate correctly.

The following:

Mail.deliver do
from MAIL_FROM
to MAIL_TO
subject "blarg"
add_file :filename => outfile
body "Attached"
end

Sends:
Attached
----==_mimepart_4af86f6e8cf7b_54632413af2633860--

Where as, flipping the body and add_file lines generates a correctly attached file but with no body (which is fine as I don't actually need the body).

ruby 1.9 support

diff --git a/vendor/gems/mail-2.1.2/lib/mail/patterns.rb b/vendor/gems/mail-2.1.2/lib/mail/patterns.rb
index 9e28807..8c3d8ec 100644
--- a/vendor/gems/mail-2.1.2/lib/mail/patterns.rb
+++ b/vendor/gems/mail-2.1.2/lib/mail/patterns.rb
@@ -9,7 +9,7 @@ module Mail
     aspecial     = %Q|()<>[]:;.\\,"|
     tspecial     = %Q|()<>[];:\\,"/?=|
     lwsp         = %Q| \t\r\n|
-    control      = %Q|\x00-\x1f\x7f-\xff|
+    control      = %Q|\x00-\x1f\x7f-\xff|.force_encoding(Encoding::BINARY)

     CRLF          = /\r\n/
     WSP           = /[#{white_space}]/

cucumber features not working

Tried running the cucumber feature in the mail project, but it had some issues.

eature: Making a new message
In order to to be able to send a message
Users should be able to
Create a message object

Scenario: Making a basic plain text email from a string # spec/features/making_a_new_message.feature:6
Given a basic email in a string # spec/features/steps/making_a_new_message_steps.rb:1
When I parse the basic email # spec/features/steps/making_a_new_message_steps.rb:5
uninitialized constant Mail::Message (NameError)
./spec/features/steps/../../../lib/mail/mail.rb:50:in new' ./spec/features/steps/making_a_new_message_steps.rb:6:in/^I parse the basic email$/'
spec/features/making_a_new_message.feature:8:in `When I parse the basic email'
Then the 'from' field should be 'bob' # spec/features/steps/making_a_new_message_steps.rb:9
| attribute | value |
| to | mikel |
| subject | Hello! |
| body | email message |

Failing Scenarios:
cucumber spec/features/making_a_new_message.feature:6 # Scenario: Making a basic plain text email from a string

1 scenario (1 failed)
3 steps (1 failed, 1 skipped, 1 passed)
0m0.006s
rake aborted!
Command failed with status (1): [/usr/local/rvm/ruby-1.8.6-p287/bin/ruby -I...]

Do you plan on using cucumber for some of your testing. Was thinking of trying to implement some imap functionality and i was going to start with cucumber.

thx.

-karl

pop3 example not working

Hi. We are trying out the pop3 example from the github page and running into an error:

 ?> Mail.defaults do
  ?>    pop3 'mail.myhost.co.jp', 995 do
  ?>      user 'mikel'

> > ```
> >  pass 'mypass'
> >  enable_tls
> > ```
> > 
> >    end
> >  end
> >   NoMethodError: undefined method `pop3' for #
> >     from (irb):30
> >     from /usr/local/rvm/gems/ruby-1.8.6-p287/gems/mail-2.1.2/lib/mail/mail.rb:106:in` instance_eval'
> >     from /usr/local/rvm/gems/ruby-1.8.6-p287/gems/mail-2.1.2/lib/mail/mail.rb:106:in `defaults'
> >     from (irb):29
> > 
> >   ?>
> > 

thx.

-karl

Why does mail add extra carriage return characters to raw_source?

We have a header


irb(main):022:0> header
=> "MIME-Version: 1.0\nDate: Mon, 17 Aug 2009 11:45:47 -0700\nReceived: by 10.150.123.13; Mon, 17 Aug 2009 11:45:47 -0700 (PDT)\nMessage-ID: <[email protected]>\nSubject: Get started with Gmail\nFrom: Gmail Team \nTo: weshop cucumber \nContent-Type: multipart/alternative; boundary=000e0cd590f0686c8a04715acf14\n"

We read it in to mail and compare it to the original header and we get false:


irb(main):023:0> header==Mail.new(header).raw_source
=> false

Turns out the Mail.raw_source has extra '\r' characters not in the original header:


irb(main):024:0> Mail.new(header).raw_source
=> "MIME-Version: 1.0\r\nDate: Mon, 17 Aug 2009 11:45:47 -0700\r\nReceived: by 10.150.123.13; Mon, 17 Aug 2009 11:45:47 -0700 (PDT)\r\nMessage-ID: [email protected]\r\nSubject: Get started with Gmail\r\nFrom: Gmail Team [email protected]\r\nTo: weshop cucumber [email protected]\r\nContent-Type: multipart/alternative; boundary=000e0cd590f0686c8a04715acf14"

thx.

-karl

Freezing in rails 2.3.4, server startup fails

mail/lib/mail.rb line 30 ff
begin
require 'active_support/core_ext/object/blank'
rescue LoadError
# Unneeded for Active Support <= 3.0.pre
end

Mail froozen as gem in rails i get a startup error:
/usr/local/lib/site_ruby/1.8/rubygems.rb:270:in `activate': You have a nil object when you didn't expect it! (NoMethodError)
You might have expected an instance of Array.
The error occurred while evaluating nil.map

I dont know how this behaves in other rails versions but i got another error than the rescued LoadError. So after commenting out the specific error my rails instance would start.

smtp helo is not being set

wrong instance variable name in
Class smtp
def helo(value = nil)
value ? @help = value : @helo ||= 'localhost.localdomain'
end

@help should probably be @helo

bcc field missing encode

When calling message.bcc an empty string is returned due to the missing encoding in the bcc_field class

Message ID generation Issue

I'm attempting to use the mail gem but am running into an issue. It seems that the autogenerated Message id that is assigned is invalid.

/usr/local/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/elements/message_ids_element.rb:12:in initialize': MessageIdsElement can not parse |[email protected]| (Mail::Field::ParseError) Reason was: Expected one of ", !, #, $, %, &, ', *, +, -, /, =, ?, ^, _,, {, |, }, ~, @ at line 1, column 21 (byte 21) after <4af86a8e36961_52be.

This seems to be an issue with the %x encoding of Thread.current.object_id on this version of ruby.

[dj2@Titania:~] ruby -v ruby 1.8.7 (2008-06-09 patchlevel 17) [i686-linux]

irb(main):014:0> Thread.current.object_id
=> -605320998

irb(main):015:0> sprintf("%x", (Thread.current.object_id))
=> "..fdbeb88da"

Changing it to make the object_id a positive number seems to fix the issue

irb(main):003:0> sprintf("%x", (Thread.current.object_id).abs)
=> "24120f22"

Message ID not handling multiple periods in left hand side

This message ID: "[email protected]"

Produces the following:

/usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/elements/message_ids_element.rb:12:in `initialize': MessageIdsElement can not parse |<[email protected]>| (Mail::Field::ParseError)
Reason was: Expected one of ", !, #, $, %, &, ', *, +, -, /, =, ?, ^, _, `, {, |, }, ~, @ at line 1, column 21 (byte 21) after <4afb664ca3078_48dc.
from /usr/lib/ruby/gems/1.8/gems/mail-  1.2.1/lib/mail/fields/common/common_message_id.rb:16:in `new'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/fields/common/common_message_id.rb:16:in `element'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/fields/common/common_message_id.rb:20:in `message_id'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/fields/message_id_field.rb:56:in `message_ids'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/fields/common/common_message_id.rb:30:in `do_encode'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/fields/message_id_field.rb:64:in `encoded'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/field.rb:120:in `send'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/field.rb:120:in `method_missing'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/header.rb:163:in `encoded'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/header.rb:162:in `each'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/header.rb:162:in `encoded'
from /usr/lib/ruby/gems/1.8/gems/mail-1.2.1/lib/mail/message.rb:591:in `to_s'
from a.rb:9

README add_file examples don't seem to work

The readme says the add_file syntax is:
add_file 'New Header Image', '/somefile.png'

Which, when I tried gave an error. I needed to do:
add_file '/somefile.png'

for the method to work successfully

Read mail from $stdin

I know that TMail does this, and that's what I am using for now. I am not sure if I am just missing something in the api to do this.

Unneeded OpenSSL::SSL::VERIFY_NONE passed in to smtp connection?

Hello,

Awesome library, thanks :) Ran into a bit of a problem and wanted to check what was expected.

Line 27 of lib/mail/network/deliverable calls:

smtp.enable_tls(OpenSSL::SSL::VERIFY_NONE)

The actual net/smtp library sets that argument to @ssl_context in the method enable_tls, line 305 of net/smtp.rb.

Further in the file, when OpenSSL is called like so, in line 577 of net/smtp.rb:

 s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)

OpenSSL::SSL::SSLSocket.new raises an error because @ssl_context is set to a fixnum (OpenSSL::SSL::VERIFY_NONE appears to be hard coded to return 0) and it's expecting an actual context object instead.

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/smtp.rb:577:in `initialize':
wrong argument (Fixnum)! (Expected kind of OpenSSL::SSL::SSLContext) (TypeError)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/smtp.rb:577:in `new'

If line 27 of mail's lib/mail/network/deliverable is changed to not pass in the VERIFY_NONE argument I am able to send mail through a tls enabled SMTP server.

What is the VERIFY_NONE argument supposed to do? I've checked this in both 1.8.7 and 1.9 and it appears to cause the same problem.

Thanks,

-- Jim

Character encoding problems with unicode strings

Apologies if the title of this bug isn't very accurate; I confess I can't quite get my head around these encoding issues, so I'll just try and explain the original problem I was having, how I tried (and failed) to solve it using Mail and how I eventually solved it by using the latest TMail.

I'm extracting content from email subjects and was using the version of TMail bundled with Rails 2.3.5. (1.2.3). I noticed that some of the parsed subjects had seemingly random spaces inserted into them that weren't present in the original email. I eventually managed to track this down to what I think was a bug in TMail, where it would not handle folded headers. This meant a header that looked like this:

Subject: =?ISO-8859-1?Q?some test da?=
        =?ISO-8859-1?Q?ta and some more text?=

Would end up looking like "some test da ta some more text" instead of "some test data some more text".

Long story short: bundling the latest tmail (1.2.7) fixed this issue although I'm not sure which version this was fixed in, but great!

However, on the way to fixing this I tried using Mail instead of TMail. I thought I was onto a winner as straight out of the box it handled the folded subject perfectly, until I noticed a problem.

One example string included some pound (sterling) symbols, e.g.: "=?ISO-8859-1?Q?This cost =A3400?=".

The expected output is "This cost £400" and TMail handled this correctly. However with Mail, I seemed to end up with an octal representation, i.e. "This cost \243400" instead, which when displayed on the page (or in the Ruby console) simply output as a ? character.

I'm not sure what exactly the issue is but Mail seems to be doing something different to TMail. I'd love to offer a patch but wouldn't know where to start so hopefully you'll find time to look at this.

Encode values before calling treetop parser

I ran into a couple of issues when creating an email because my address fields and the attachments filename contain strings with special chars / umlauts (üöä).

For now i am manually, escaping those fields with something like:

str.ascii_only? ? str : Mail::Encodings.b_value_encode(str, 'UTF-8')

but this should be done before parsing to prevent treetop errors.

Header parsing – warnings

I get this with every message on my workplace's Exchange server:

WARNING: Could not parse (and so ignorning) 'X-MS-Has-Attach:'
WARNING: Could not parse (and so ignorning) 'X-MS-TNEF-Correlator:'

Headers look like this (in brackets to show trailing spaces, if you need them):

[X-Ms-Has-Attach: yes ]

[X-MS-TNEF-Correlator: ]

empty/nil cc/bcc field causes exception (Mail::Field::ParseError)

require 'mail'
=> true
Mail.deliver do
?> from '[email protected]'
to '[email protected]'
cc ''
subject 'testing'
body 'this is a test'
end
Mail::Field::ParseError: AddressListsParser can not parse ||
Reason was: Expected one of
, (, !, #, $, %, &, ', *, +, -, /, =, ?, ^, _, `, {, |, }, ~, ", ., <, , at line 1, column 1 (byte 1) after

from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/elements/address_list.rb:25:in `initialize'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/fields/common/common_address.rb:70:in `new'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/fields/common/common_address.rb:70:in `tree'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/fields/common/common_address.rb:20:in `addresses'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/field.rb:120:in `method_missing'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/message.rb:262:in `block in destinations'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/message.rb:262:in `map'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/message.rb:262:in `destinations'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/network/delivery_methods/smtp.rb:62:in `deliver!'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/network/deliverable.rb:11:in `perform_delivery!'
from /usr/local/lib/ruby/gems/1.9.1/gems/mail-1.2.5/lib/mail/mail.rb:122:in `deliver'
from (irb):2
from /usr/local/bin/irb:12:in `<main>'

Content Transfer Encoding

I get this error message:

undefined method `encoding' for nil:NilClass
# from line 19 in part.rb

Parsing attachments for this email: https://gist.github.com/988687576aac10ff91f0

But I can't quite figure out what's supposed to happen, there's an attachment nested inside another, with the same mime boundaries used. Is that legit?

Mail::Message#to_s doesn't store bcc field

I came across this when storing Mail::Messages in my Delayed::Job queue. Long story short, serializing the Mail::Message instance failed, so I stored it as a string, then created a new mail from that string. I had tests to cover some bcc field info. I created a message using Mail.new, set bcc fields, then called to_s to pass if of the job, except bcc wasn't there when parsing the mail from string.

Here's a console session to illustrate the problem: http://gist.github.com/345865

How to delete an attachment?

For storing e-mails in the database I want to remove the attachments from the mail (and store them in the filesystem). I can't find any support for removing attachments from an existing e-mail. What is the prefered way?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.