Sha256: dbd98f3fc0eef18139a81f24873d42d5e070c7593abcbb254110e9cf73d2dd6d

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

require "mail"

module Email; end

module Email::Mboxrd
  class Message
    attr_reader :supplied_body

    def self.from_serialized(serialized)
      cleaned = serialized.gsub(/^>(>*From)/, "\\1")
      # Serialized messages in this format *should* start with a line
      #   From xxx yy zz
      if cleaned.start_with?("From ")
        cleaned = cleaned.sub(/^From .*[\r\n]*/, "")
      end
      new(cleaned)
    end

    def initialize(supplied_body)
      @supplied_body = supplied_body.clone
      @supplied_body.force_encoding("binary")
    end

    def to_serialized
      "From " + from + "\n" + mboxrd_body + "\n"
    end

    private

    def parsed
      @parsed ||= Mail.new(supplied_body)
    end

    def best_from
      if parsed.from.is_a?(Enumerable)
        parsed.from.each do |addr|
          return addr if addr
        end
      end

      return parsed.sender if parsed.sender
      return parsed.envelope_from if parsed.envelope_from
      return parsed.return_path if parsed.return_path

      return ""
    end

    def from
      @from ||=
        begin
          from = best_from
          from << " " + asctime if asctime != ""
          from
        end
    end

    def mboxrd_body
      @mboxrd_body ||=
        begin
          @mboxrd_body = add_extra_quote(supplied_body)
          @mboxrd_body += "\n" if !@mboxrd_body.end_with?("\n")
          @mboxrd_body
        end
    end

    def add_extra_quote(body)
      # The mboxrd format requires that lines starting with 'From'
      # be prefixed with a '>' so that any remaining lines which start with
      # 'From ' can be taken as the beginning of messages.
      # http://www.digitalpreservation.gov/formats/fdd/fdd000385.shtml
      # Here we add an extra '>' before any "From" or ">From".
      body.gsub(/\n(>*From)/, "\n>\\1")
    end

    def asctime
      @asctime ||= date ? date.asctime : ""
    end

    def date
      parsed.date
    rescue
      nil
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
imap-backup-1.4.0 lib/email/mboxrd/message.rb