Class: Mail::Body

### Home Classes Methods

### In Files

- lib/mail/body.rb

### Parent

Object

### Methods

- ::new
- #<<
- #==
- #=~
- #boundary
- #boundary=
- #charset
- #charset=
- #decoded
- #empty?
- #encoded
- #encoding
- #encoding=
- #epilogue
- #epilogue=
- #get_best_encoding
- #include?
- #match
- #multipart?
- #only_us_ascii?
- #parts
- #preamble
- #preamble=
- #raw_source
- #set_sort_order
- #sort_parts!
- #split!
- #to_s

### Files

- 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::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::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::EncodingError
- 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
- Net
- Net::SMTP
- Object
- String

No matching classes.

# Mail::Body

# Body

The body is where the text of the email is stored. Mail treats the body as a single object. The body itself has no information about boundaries used in the MIME standard, it just looks at its content as either a single block of text, or (if it is a multipart message) as an array of blocks of text.

A body has to be told to split itself up into a multipart message by calling split with the correct boundary. This is because the body object has no way of knowing what the correct boundary is for itself (there could be many boundaries in a body in the case of a nested MIME text).

Once split is called, Mail::Body will slice itself up on this boundary, assigning anything that appears before the first part to the preamble, and anything that appears after the closing boundary to the epilogue, then each part gets initialized into a Mail::Part object.

The boundary that is used to split up the Body is also stored in the Body object for use on encoding itself back out to a string. You can overwrite this if it needs to be changed.

On encoding, the body will return the preamble, then each part joined by the boundary, followed by a closing boundary string and then the epilogue.

### Public Class Methods

new(string = '') click to toggle source

    # File lib/mail/body.rb, line 28
    def initialize(string = '')
      @boundary = nil
      @preamble = nil
      @epilogue = nil
      @charset  = nil
      @part_sort_order = [ "text/plain", "text/enriched", "text/html" ]
      @parts = Mail::PartsList.new
      if string.blank?
        @raw_source = ''
      else
        # Do join first incase we have been given an Array in Ruby 1.9
        if string.respond_to?(:join)
          @raw_source = string.join('')
        elsif string.respond_to?(:to_s)
          @raw_source = string.to_s
        else
          raise "You can only assign a string or an object that responds_to? :join or :to_s to a body."
        end
      end
      @encoding = (only_us_ascii? ? '7bit' : '8bit')
      set_charset
    end

### Public Instance Methods

<<( val ) click to toggle source

    # File lib/mail/body.rb, line 249
    def <<( val )
      if @parts
        @parts << val
      else
        @parts = Mail::PartsList.new[val]
      end
    end

==(other) click to toggle source

Matches this body with another body. Also matches the decoded value of this body with a string.

Examples:

    body = Mail::Body.new('The body')
    body == body #=> true

    body = Mail::Body.new('The body')
    body == 'The body' #=> true

    body = Mail::Body.new("VGhlIGJvZHk=\n")
    body.encoding = 'base64'
    body == "The body" #=> true

    # File lib/mail/body.rb, line 65
    def ==(other)
      if other.class == String
        self.decoded == other
      else
        super
      end
    end

=~(regexp) click to toggle source

Accepts a string and performs a regular expression against the decoded text

Examples:

    body = Mail::Body.new('The body')
    body =~ /The/ #=> 0

    body = Mail::Body.new("VGhlIGJvZHk=\n")
    body.encoding = 'base64'
    body =~ /The/ #=> 0

    # File lib/mail/body.rb, line 83
    def =~(regexp)
      self.decoded =~ regexp
    end

boundary() click to toggle source

Returns the boundary used by the body

    # File lib/mail/body.rb, line 236
    def boundary
      @boundary
    end

boundary=( val ) click to toggle source

Allows you to change the boundary of this Body object

    # File lib/mail/body.rb, line 241
    def boundary=( val )
      @boundary = val
    end

charset() click to toggle source

    # File lib/mail/body.rb, line 186
    def charset
      @charset
    end

charset=( val ) click to toggle source

    # File lib/mail/body.rb, line 190
    def charset=( val )
      @charset = val
    end

decoded() click to toggle source

    # File lib/mail/body.rb, line 174
    def decoded
      if !Encodings.defined?(encoding)
        raise UnknownEncodingType, "Don't know how to decode #{encoding}, please call #encoded and decode it yourself."
      else
        Encodings.get_encoding(encoding).decode(raw_source)
      end
    end

empty?() click to toggle source

    # File lib/mail/body.rb, line 272
    def empty?
      !!raw_source.to_s.empty?
    end

encoded(transfer_encoding = '8bit') click to toggle source

Returns a body encoded using transfer_encoding. Multipart always uses an identiy encoding (i.e. no encoding). Calling this directly is not a good idea, but supported for compatibility TODO: Validate that preamble and epilogue are valid for requested encoding

    # File lib/mail/body.rb, line 149
    def encoded(transfer_encoding = '8bit')
      if multipart?
        self.sort_parts!
        encoded_parts = parts.map { |p| p.encoded }
        ([preamble] + encoded_parts).join(crlf_boundary) + end_boundary + epilogue.to_s
      else
        be = get_best_encoding(transfer_encoding)
        dec = Mail::Encodings::get_encoding(encoding)
        enc = Mail::Encodings::get_encoding(be)
        if transfer_encoding == encoding and dec.nil?
            # Cannot decode, so skip normalization
            raw_source
        else
            # Decode then encode to normalize and allow transforming
            # from base64 to Q-P and vice versa
            decoded = dec.decode(raw_source)
            if defined?(Encoding) && charset && charset != "US-ASCII"
              decoded.encode!(charset)
              decoded.force_encoding('BINARY') unless Encoding.find(charset).ascii_compatible?
            end
            enc.encode(decoded)
        end
      end
    end

encoding(val = nil) click to toggle source

    # File lib/mail/body.rb, line 194
    def encoding(val = nil)
      if val
        self.encoding = val
      else
        @encoding
      end
    end

encoding=( val ) click to toggle source

    # File lib/mail/body.rb, line 202
    def encoding=( val )
      @encoding = if val == "text" || val.blank?
          (only_us_ascii? ? '7bit' : '8bit')
      else
          val
      end
    end

epilogue() click to toggle source

Returns the epilogue (any text that is after the last MIME boundary)

    # File lib/mail/body.rb, line 221
    def epilogue
      @epilogue
    end

epilogue=( val ) click to toggle source

Sets the epilogue to a string (adds text after the last MIME boundary)

    # File lib/mail/body.rb, line 226
    def epilogue=( val )
      @epilogue = val
    end

get_best_encoding(target) click to toggle source

    # File lib/mail/body.rb, line 140
    def get_best_encoding(target)
      target_encoding = Mail::Encodings.get_encoding(target)
      target_encoding.get_best_compatible(encoding, raw_source)
    end

include?(other) click to toggle source

Accepts anything that responds to to_s and checks if it's a substring of the decoded text

Examples:

    body = Mail::Body.new('The body')
    body.include?('The') #=> true

    body = Mail::Body.new("VGhlIGJvZHk=\n")
    body.encoding = 'base64'
    body.include?('The') #=> true

    # File lib/mail/body.rb, line 111
    def include?(other)
      self.decoded.include?(other.to_s)
    end

match(regexp) click to toggle source

Accepts a string and performs a regular expression against the decoded text

Examples:

    body = Mail::Body.new('The body')
    body.match(/The/) #=> #<MatchData "The">

    body = Mail::Body.new("VGhlIGJvZHk=\n")
    body.encoding = 'base64'
    body.match(/The/) #=> #<MatchData "The">

    # File lib/mail/body.rb, line 97
    def match(regexp)
      self.decoded.match(regexp)
    end

multipart?() click to toggle source

Returns true if there are parts defined in the body

    # File lib/mail/body.rb, line 231
    def multipart?
      true unless parts.empty?
    end

only_us_ascii?() click to toggle source

    # File lib/mail/body.rb, line 268
    def only_us_ascii?
      !(raw_source =~ /[^\x01-\x7f]/)
    end

parts() click to toggle source

    # File lib/mail/body.rb, line 245
    def parts
      @parts
    end

preamble() click to toggle source

Returns the preamble (any text that is before the first MIME boundary)

    # File lib/mail/body.rb, line 211
    def preamble
      @preamble
    end

preamble=( val ) click to toggle source

Sets the preamble to a string (adds text before the first MIME boundary)

    # File lib/mail/body.rb, line 216
    def preamble=( val )
      @preamble = val
    end

raw_source() click to toggle source

Returns the raw source that the body was initialized with, without any tampering

    # File lib/mail/body.rb, line 136
    def raw_source
      @raw_source
    end

set_sort_order(order) click to toggle source

Allows you to set the sort order of the parts, overriding the default sort order. Defaults to 'text/plain', then 'text/enriched', then 'text/html' with any other content type coming after.

    # File lib/mail/body.rb, line 118
    def set_sort_order(order)
      @part_sort_order = order
    end

sort_parts!() click to toggle source

Allows you to sort the parts according to the default sort order, or the sort order you set with :set_sort_order.

sort_parts! is also called from :encode, so there is no need for you to call this explicitly

    # File lib/mail/body.rb, line 126
    def sort_parts!
      @parts.each do |p|
        p.body.set_sort_order(@part_sort_order)
        @parts.sort!(@part_sort_order)
        p.body.sort_parts!
      end
    end

split!(boundary) click to toggle source

    # File lib/mail/body.rb, line 257
    def split!(boundary)
      self.boundary = boundary
      parts = raw_source.split(/(?:\A|\r\n)--#{Regexp.escape(boundary)}(?=(?:--)?\s*$)/)
      # Make the preamble equal to the preamble (if any)
      self.preamble = parts[0].to_s.strip
      # Make the epilogue equal to the epilogue (if any)
      self.epilogue = parts[-1].to_s.sub('--', '').strip
      parts[1...-1].to_a.each { |part| @parts << Mail::Part.new(part) }
      self
    end

to_s() click to toggle source

    # File lib/mail/body.rb, line 182
    def to_s
      decoded
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.