Module: Mail::Encodings

### Home Classes Methods

### In Files

- lib/mail/encodings/transfer_encoding.rb
- lib/mail/encodings/7bit.rb
- lib/mail/encodings/quoted_printable.rb
- lib/mail/encodings/8bit.rb
- lib/mail/encodings/base64.rb
- lib/mail/encodings/binary.rb
- lib/mail/encodings.rb

### Namespace

- CLASS Mail::Encodings::Base64
- CLASS Mail::Encodings::Binary
- CLASS Mail::Encodings::EightBit
- CLASS Mail::Encodings::QuotedPrintable
- CLASS Mail::Encodings::SevenBit
- CLASS Mail::Encodings::TransferEncoding

### Methods

- ::address_encode
- ::b_value_encode
- ::decode_encode
- ::defined?
- ::encode_non_usascii
- ::get_all
- ::get_encoding
- ::get_name
- ::param_decode
- ::param_encode
- ::q_value_encode
- ::register
- ::unquote_and_convert_to
- ::value_decode

### Included Modules

- Mail::Patterns

### Files

- CHANGELOG.rdoc
- TODO.rdoc
- VERSION

### Class/Module Index

Quicksearch

- Mail
- Mail::Address
- Mail::AddressContainer
- Mail::AddressLists
- Mail::AddressLists::PrimaryAddress0
- Mail::AddressLists::PrimaryAddress1
- Mail::AddressListsParser
- Mail::AttachmentsList
- Mail::BccField
- Mail::Body
- Mail::CcField
- Mail::CheckDeliveryParams
- Mail::CommentsField
- Mail::Configuration
- Mail::ContentDescriptionField
- Mail::ContentDisposition
- Mail::ContentDisposition::ContentDisposition0
- Mail::ContentDisposition::ContentDisposition1
- Mail::ContentDisposition::ContentDisposition2
- Mail::ContentDisposition::DispositionType0
- Mail::ContentDisposition::DispositionType1
- Mail::ContentDisposition::Parameter0
- Mail::ContentDisposition::Parameter1
- Mail::ContentDisposition::Value0
- Mail::ContentDispositionField
- Mail::ContentDispositionParser
- Mail::ContentIdField
- Mail::ContentLocation
- Mail::ContentLocation::Location0
- Mail::ContentLocation::Primary0
- Mail::ContentLocationField
- Mail::ContentLocationParser
- Mail::ContentTransferEncoding
- Mail::ContentTransferEncoding::Primary0
- Mail::ContentTransferEncodingElement
- Mail::ContentTransferEncodingField
- Mail::ContentTransferEncodingParser
- Mail::ContentType
- Mail::ContentType::CompositeType0
- Mail::ContentType::CompositeType1
- Mail::ContentType::ContentType0
- Mail::ContentType::ContentType1
- Mail::ContentType::ContentType2
- Mail::ContentType::DiscreteType0
- Mail::ContentType::DiscreteType1
- Mail::ContentType::DiscreteType2
- Mail::ContentType::DiscreteType3
- Mail::ContentType::DiscreteType4
- Mail::ContentType::Parameter0
- Mail::ContentType::Parameter1
- Mail::ContentType::Value0
- Mail::ContentTypeField
- Mail::ContentTypeParser
- Mail::DateField
- Mail::DateTime
- Mail::DateTime::Primary0
- Mail::DateTime::Primary1
- Mail::DateTimeParser
- Mail::Encodings
- Mail::Encodings::Base64
- Mail::Encodings::Binary
- Mail::Encodings::EightBit
- Mail::Encodings::QuotedPrintable
- Mail::Encodings::SevenBit
- Mail::Encodings::TransferEncoding
- Mail::Envelope
- Mail::EnvelopeFrom
- Mail::EnvelopeFrom::CtimeDate0
- Mail::EnvelopeFrom::Primary0
- Mail::EnvelopeFromElement
- Mail::EnvelopeFromParser
- Mail::Exim
- Mail::Field
- Mail::Field::FieldError
- Mail::FieldList
- Mail::FileDelivery
- Mail::FromField
- Mail::Header
- Mail::IMAP
- Mail::InReplyToField
- Mail::IndifferentHash
- Mail::KeywordsField
- Mail::Matchers
- Mail::Matchers::HasSentEmailMatcher
- Mail::Message
- Mail::MessageIdField
- Mail::MessageIds
- Mail::MessageIds::Primary0
- Mail::MessageIdsElement
- Mail::MessageIdsParser
- Mail::MimeVersion
- Mail::MimeVersion::Version0
- Mail::MimeVersion::Version1
- Mail::MimeVersionElement
- Mail::MimeVersionField
- Mail::MimeVersionParser
- Mail::Multibyte
- Mail::Multibyte::Chars
- Mail::Multibyte::EncodingError
- Mail::Multibyte::Unicode
- Mail::Multibyte::Unicode::Codepoint
- Mail::Multibyte::Unicode::UnicodeDatabase
- Mail::OptionalField
- Mail::POP3
- Mail::ParameterHash
- Mail::Part
- Mail::PartsList
- Mail::Patterns
- Mail::PhraseList
- Mail::PhraseLists
- Mail::PhraseLists::PrimaryPhrase0
- Mail::PhraseListsParser
- Mail::RFC2045
- Mail::RFC2045::CustomXToken0
- Mail::RFC2045Parser
- Mail::RFC2822
- Mail::RFC2822::AddrSpec0
- Mail::RFC2822::Address0
- Mail::RFC2822::AddressList0
- Mail::RFC2822::AddressList1
- Mail::RFC2822::AngleAddr0
- Mail::RFC2822::Atom0
- Mail::RFC2822::CFWS0
- Mail::RFC2822::CFWS1
- Mail::RFC2822::Comment0
- Mail::RFC2822::Comment1
- Mail::RFC2822::Date0
- Mail::RFC2822::DateTime0
- Mail::RFC2822::DateTime1
- Mail::RFC2822::Day0
- Mail::RFC2822::DayOfWeek0
- Mail::RFC2822::DomainLiteral0
- Mail::RFC2822::DomainLiteral1
- Mail::RFC2822::DomainText0
- Mail::RFC2822::DomainText1
- Mail::RFC2822::DotAtom0
- Mail::RFC2822::DotAtomText0
- Mail::RFC2822::FWS0
- Mail::RFC2822::FWS1
- Mail::RFC2822::Group0
- Mail::RFC2822::Hour0
- Mail::RFC2822::ItemName0
- Mail::RFC2822::ItemName1
- Mail::RFC2822::LocalDotAtom0
- Mail::RFC2822::LocalDotAtomText0
- Mail::RFC2822::Mailbox0
- Mail::RFC2822::MailboxList0
- Mail::RFC2822::MailboxList1
- Mail::RFC2822::MailboxListGroup0
- Mail::RFC2822::MessageIds0
- Mail::RFC2822::MessageIds1
- Mail::RFC2822::Minute0
- Mail::RFC2822::Month0
- Mail::RFC2822::MsgId0
- Mail::RFC2822::MsgIdDomainText0
- Mail::RFC2822::MsgIdDomainText1
- Mail::RFC2822::MsgIdDotAtomText0
- Mail::RFC2822::MsgIdValue0
- Mail::RFC2822::NameAddr0
- Mail::RFC2822::NameValList0
- Mail::RFC2822::NameValList1
- Mail::RFC2822::NameValList2
- Mail::RFC2822::NameValPair0
- Mail::RFC2822::NoFoldLiteral0
- Mail::RFC2822::NoFoldQuote0
- Mail::RFC2822::Path0
- Mail::RFC2822::PhraseList0
- Mail::RFC2822::PhraseList1
- Mail::RFC2822::QuotedDomain0
- Mail::RFC2822::QuotedPair0
- Mail::RFC2822::QuotedString0
- Mail::RFC2822::QuotedString1
- Mail::RFC2822::Received0
- Mail::RFC2822::Return0
- Mail::RFC2822::Second0
- Mail::RFC2822::Time0
- Mail::RFC2822::TimeOfDay0
- Mail::RFC2822::TimeOfDay1
- Mail::RFC2822::Year0
- Mail::RFC2822::Zone0
- Mail::RFC2822Obsolete
- Mail::RFC2822Obsolete::ObsAddrList0
- Mail::RFC2822Obsolete::ObsAddrList1
- Mail::RFC2822Obsolete::ObsAngleAddr0
- Mail::RFC2822Obsolete::ObsBcc0
- Mail::RFC2822Obsolete::ObsCc0
- Mail::RFC2822Obsolete::ObsComments0
- Mail::RFC2822Obsolete::ObsDay0
- Mail::RFC2822Obsolete::ObsDay1
- Mail::RFC2822Obsolete::ObsDayOfWeek0
- Mail::RFC2822Obsolete::ObsDomain0
- Mail::RFC2822Obsolete::ObsDomain1
- Mail::RFC2822Obsolete::ObsDomainList0
- Mail::RFC2822Obsolete::ObsDomainList1
- Mail::RFC2822Obsolete::ObsFWS0
- Mail::RFC2822Obsolete::ObsFWS1
- Mail::RFC2822Obsolete::ObsFrom0
- Mail::RFC2822Obsolete::ObsHour0
- Mail::RFC2822Obsolete::ObsHour1
- Mail::RFC2822Obsolete::ObsInReplyTo0
- Mail::RFC2822Obsolete::ObsKeywords0
- Mail::RFC2822Obsolete::ObsLocalPart0
- Mail::RFC2822Obsolete::ObsLocalPart1
- Mail::RFC2822Obsolete::ObsMboxList0
- Mail::RFC2822Obsolete::ObsMboxList1
- Mail::RFC2822Obsolete::ObsMessageId0
- Mail::RFC2822Obsolete::ObsMinute0
- Mail::RFC2822Obsolete::ObsMinute1
- Mail::RFC2822Obsolete::ObsMonth0
- Mail::RFC2822Obsolete::ObsOptional0
- Mail::RFC2822Obsolete::ObsOrigDate0
- Mail::RFC2822Obsolete::ObsPhraseList0
- Mail::RFC2822Obsolete::ObsPhraseList1
- Mail::RFC2822Obsolete::ObsQp0
- Mail::RFC2822Obsolete::ObsReceived0
- Mail::RFC2822Obsolete::ObsReferences0
- Mail::RFC2822Obsolete::ObsReplyTo0
- Mail::RFC2822Obsolete::ObsResentBcc0
- Mail::RFC2822Obsolete::ObsResentCc0
- Mail::RFC2822Obsolete::ObsResentDate0
- Mail::RFC2822Obsolete::ObsResentFrom0
- Mail::RFC2822Obsolete::ObsResentMid0
- Mail::RFC2822Obsolete::ObsResentRply0
- Mail::RFC2822Obsolete::ObsResentSend0
- Mail::RFC2822Obsolete::ObsResentTo0
- Mail::RFC2822Obsolete::ObsReturn0
- Mail::RFC2822Obsolete::ObsRoute0
- Mail::RFC2822Obsolete::ObsSecond0
- Mail::RFC2822Obsolete::ObsSecond1
- Mail::RFC2822Obsolete::ObsSender0
- Mail::RFC2822Obsolete::ObsSubject0
- Mail::RFC2822Obsolete::ObsText0
- Mail::RFC2822Obsolete::ObsText1
- Mail::RFC2822Obsolete::ObsTo0
- Mail::RFC2822Obsolete::ObsYear0
- Mail::RFC2822Obsolete::ObsYear1
- Mail::RFC2822ObsoleteParser
- Mail::RFC2822Parser
- Mail::Received
- Mail::Received::Primary0
- Mail::ReceivedElement
- Mail::ReceivedField
- Mail::ReceivedParser
- Mail::ReferencesField
- Mail::ReplyToField
- Mail::ResentBccField
- Mail::ResentCcField
- Mail::ResentDateField
- Mail::ResentFromField
- Mail::ResentMessageIdField
- Mail::ResentSenderField
- Mail::ResentToField
- Mail::Retriever
- Mail::ReturnPathField
- Mail::Ruby18
- Mail::Ruby19
- Mail::RubyVer
- Mail::SMTP
- Mail::SMTPConnection
- Mail::SenderField
- Mail::Sendmail
- Mail::StructuredField
- Mail::SubjectField
- Mail::TestMailer
- Mail::TestRetriever
- Mail::ToField
- Mail::UnstructuredField
- Mail::Utilities
- Mail::VERSION
- ActiveSupport
- ActiveSupport::Multibyte
- Net
- Net::SMTP
- Object
- String

No matching classes.

# Mail::Encodings

### Public Class Methods

address_encode(address, charset = 'utf-8') click to toggle source

    # File lib/mail/encodings.rb, line 174
    def Encodings.address_encode(address, charset = 'utf-8')
      if address.is_a?(Array)
        # loop back through for each element
        address.compact.map { |a| Encodings.address_encode(a, charset) }.join(", ")
      else
        # find any word boundary that is not ascii and encode it
        encode_non_usascii(address, charset) if address
      end
    end

b_value_encode(encoded_str, encoding = nil) click to toggle source

Encode a string with Base64 Encoding and returns it ready to be inserted as a value for a field, that is, in the =?<charset>?B?<string>?= format

Example:

    Encodings.b_value_encode('This is あ string', 'UTF-8')
    #=> "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?="

    # File lib/mail/encodings.rb, line 211
    def Encodings.b_value_encode(encoded_str, encoding = nil)
      return encoded_str if encoded_str.to_s.ascii_only?
      string, encoding = RubyVer.b_value_encode(encoded_str, encoding)
      map_lines(string) do |str|
        "=?#{encoding}?B?#{str.chomp}?="
      end.join(" ")
    end

decode_encode(str, output_type) click to toggle source

Decodes or encodes a string as needed for either Base64 or QP encoding types in the =?<encoding>??<string>?=“ format.

The output type needs to be :decode to decode the input string or :encode to encode the input string. The character set used for encoding will either be the value of $KCODE for Ruby < 1.9 or the encoding on the string passed in.

On encoding, will only send out Base64 encoded strings.

    # File lib/mail/encodings.rb, line 97
    def Encodings.decode_encode(str, output_type)
      case
      when output_type == :decode
        Encodings.value_decode(str)
      else
        if str.ascii_only?
          str
        else
          Encodings.b_value_encode(str, find_encoding(str))
        end
      end
    end

defined?( str ) click to toggle source

Is the encoding we want defined?

Example:

    Encodings.defined?(:base64) #=> true

    # File lib/mail/encodings.rb, line 28
    def Encodings.defined?( str )
      @transfer_encodings.include? get_name(str)
    end

encode_non_usascii(address, charset) click to toggle source

    # File lib/mail/encodings.rb, line 184
    def Encodings.encode_non_usascii(address, charset)
      return address if address.ascii_only? or charset.nil?
      us_ascii = %{\x00-\x7f}
      # Encode any non usascii strings embedded inside of quotes
      address = address.gsub(/(".*?[^#{us_ascii}].*?")/) { |s| Encodings.b_value_encode(unquote(s), charset) }
      # Then loop through all remaining items and encode as needed
      tokens = address.split(/\s/)
      map_with_index(tokens) do |word, i|
        if word.ascii_only?
          word
        else
          previous_non_ascii = i>0 && tokens[i-1] && !tokens[i-1].ascii_only?
          if previous_non_ascii #why are we adding an extra space here?
            word = " #{word}"
          end
          Encodings.b_value_encode(word, charset)
        end
      end.join(' ')
    end

get_all() click to toggle source

    # File lib/mail/encodings.rb, line 44
    def Encodings.get_all
      @transfer_encodings.values
    end

get_encoding( str ) click to toggle source

Gets a defined encoding type, QuotedPrintable or Base64 for now.

Each encoding needs to be defined as a Mail::Encodings::ClassName for this to work, allows us to add other encodings in the future.

Example:

    Encodings.get_encoding(:base64) #=> Mail::Encodings::Base64

    # File lib/mail/encodings.rb, line 40
    def Encodings.get_encoding( str )
      @transfer_encodings[get_name(str)]
    end

get_name(enc) click to toggle source

    # File lib/mail/encodings.rb, line 48
    def Encodings.get_name(enc)
      enc = enc.to_s.gsub("-", "_").downcase
    end

param_decode(str, encoding) click to toggle source

Decodes a parameter value using URI Escaping.

Example:

    Mail::Encodings.param_decode("This%20is%20fun", 'us-ascii') #=> "This is fun"

    str = Mail::Encodings.param_decode("This%20is%20fun", 'iso-8559-1')
    str.encoding #=> 'ISO-8859-1'      ## Only on Ruby 1.9
    str #=> "This is fun"

    # File lib/mail/encodings.rb, line 85
    def Encodings.param_decode(str, encoding)
      RubyVer.param_decode(str, encoding)
    end

param_encode(str) click to toggle source

Encodes a parameter value using URI Escaping, note the language field ‘en’ can be set using Mail::Configuration, like so:

    Mail.defaults do
      param_encode_language 'jp'
    end

The character set used for encoding will either be the value of $KCODE for Ruby < 1.9 or the encoding on the string passed in.

Example:

    Mail::Encodings.param_encode("This is fun") #=> "us-ascii'en'This%20is%20fun"

    # File lib/mail/encodings.rb, line 65
    def Encodings.param_encode(str)
      case
      when str.ascii_only? && str =~ TOKEN_UNSAFE
        %{"#{str}"}
      when str.ascii_only?
        str
      else
        RubyVer.param_encode(str)
      end
    end

q_value_encode(encoded_str, encoding = nil) click to toggle source

Encode a string with Quoted-Printable Encoding and returns it ready to be inserted as a value for a field, that is, in the =?<charset>?Q?<string>?= format

Example:

    Encodings.q_value_encode('This is あ string', 'UTF-8')
    #=> "=?UTF-8?Q?This_is_=E3=81=82_string?="

    # File lib/mail/encodings.rb, line 226
    def Encodings.q_value_encode(encoded_str, encoding = nil)
      return encoded_str if encoded_str.to_s.ascii_only?
      string, encoding = RubyVer.q_value_encode(encoded_str, encoding)
      string.gsub!("=\r\n", '') # We already have limited the string to the length we want
      map_lines(string) do |str|
        "=?#{encoding}?Q?#{str.chomp.gsub(/ /, '_')}?="
      end.join(" ")
    end

register(name, cls) click to toggle source

Register transfer encoding

Example

Encodings.register "base64", Mail::Encodings::Base64

    # File lib/mail/encodings.rb, line 19
    def Encodings.register(name, cls)
        @transfer_encodings[get_name(name)] = cls
    end

unquote_and_convert_to(str, to_encoding) click to toggle source

Takes an encoded string of the format =?<encoding>??<string>?=

    # File lib/mail/encodings.rb, line 147
    def Encodings.unquote_and_convert_to(str, to_encoding)
      output = value_decode( str ).to_s # output is already converted to UTF-8

      if 'utf8' == to_encoding.to_s.downcase.gsub("-", "")
        output
      elsif to_encoding
        begin
          if RUBY_VERSION >= '1.9'
            output.encode(to_encoding)
          else
            require 'iconv'
            Iconv.iconv(to_encoding, 'UTF-8', output).first
          end
        rescue Iconv::IllegalSequence, Iconv::InvalidEncoding, Errno::EINVAL
          # the 'from' parameter specifies a charset other than what the text
          # actually is...not much we can do in this case but just return the
          # unconverted text.
          #
          # Ditto if either parameter represents an unknown charset, like
          # X-UNKNOWN.
          output
        end
      else
        output
      end
    end

value_decode(str) click to toggle source

Decodes a given string as Base64 or Quoted Printable, depending on what type it is.

String has to be of the format =?<encoding>??<string>?=

    # File lib/mail/encodings.rb, line 114
    def Encodings.value_decode(str)
      # Optimization: If there's no encoded-words in the string, just return it
      return str unless str =~ /\=\?[^?]+\?[QB]\?[^?]+?\?\=/mi

      lines = collapse_adjacent_encodings(str)

      # Split on white-space boundaries with capture, so we capture the white-space as well
      lines.map do |line|
        line.split(/([ \t])/).map do |text|
          if text.index('=?').nil?
            text
          else
            # Search for occurences of quoted strings or plain strings
            text.scan(/(                                 # Group around entire regex to include it in matches
                        \=\?[^?]+\?([QB])\?[^?]+?\?\=    # Quoted String with subgroup for encoding method
                        |                                # or
                        .+?(?=\=\?|$)                    # Plain String
                      )/mi).map do |matches|
              string, method = *matches
              if    method == 'b' || method == 'B'
                b_value_decode(string)
              elsif method == 'q' || method == 'Q'
                q_value_decode(string)
              else
                string
              end
            end
          end
        end
      end.flatten.join("")
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.