Class: Mail::Message

Inherits:
Object
  • Object
show all
Defined in:
lib/mail/message.rb

Overview

The Message class provides a single point of access to all things to do with an email message.

You create a new email message by calling the Mail::Message.new method, or just Mail.new

A Message object by default has the following objects inside it:

  • A Header object which contains all information and settings of the header of the email

  • Body object which contains all parts of the email that are not part of the header, this includes any attachments, body text, MIME parts etc.

Per RFC2822

2.1. General Description

 At the most basic level, a message is a series of characters.  A
 message that is conformant with this standard is comprised of
 characters with values in the range 1 through 127 and interpreted as
 US-ASCII characters [ASCII].  For brevity, this document sometimes
 refers to this range of characters as simply "US-ASCII characters".

 Note: This standard specifies that messages are made up of characters
 in the US-ASCII range of 1 through 127.  There are other documents,
 specifically the MIME document series [RFC2045, RFC2046, RFC2047,
 RFC2048, RFC2049], that extend this standard to allow for values
 outside of that range.  Discussion of those mechanisms is not within
 the scope of this standard.

 Messages are divided into lines of characters.  A line is a series of
 characters that is delimited with the two characters carriage-return
 and line-feed; that is, the carriage return (CR) character (ASCII
 value 13) followed immediately by the line feed (LF) character (ASCII
 value 10).  (The carriage-return/line-feed pair is usually written in
 this document as "CRLF".)

 A message consists of header fields (collectively called "the header
 of the message") followed, optionally, by a body.  The header is a
 sequence of lines of characters with special syntax as defined in
 this standard. The body is simply a sequence of characters that
 follows the header and is separated from the header by an empty line
 (i.e., a line with nothing preceding the CRLF).

Direct Known Subclasses

Part

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args, &block) ⇒ Message

Making an email

You can make an new mail object via a block, passing a string, file or direct assignment.

Making an email via a block

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

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

If may also pass a block with no arguments, in which case it will be evaluated in the scope of the new message instance:

mail = Mail.new do
  from '[email protected]'
  # …
end

Making an email via passing a string

mail = Mail.new("To: [email protected]\r\nSubject: Hello\r\n\r\nHi there!")
mail.body.to_s #=> 'Hi there!'
mail.subject   #=> 'Hello'
mail.to        #=> '[email protected]'

Making an email from a file

mail = Mail.read('path/to/file.eml')
mail.body.to_s #=> 'Hi there!'
mail.subject   #=> 'Hello'
mail.to        #=> '[email protected]'

Making an email via assignment

You can assign values to a mail object via four approaches:

  • Message#field_name=(value)

  • Message#field_name(value)

  • Message#=(value)

  • Message#=(value)

Examples:

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

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


107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/mail/message.rb', line 107

def initialize(*args, &block)
  @body = nil
  @body_raw = nil
  @separate_parts = false
  @text_part = nil
  @html_part = nil
  @errors = nil
  @header = nil
  @charset = self.class.default_charset
  @defaulted_charset = true

  @smtp_envelope_from = nil
  @smtp_envelope_to = nil

  @perform_deliveries = true
  @raise_delivery_errors = true

  @delivery_handler = nil

  @delivery_method = Mail.delivery_method.dup

  @transport_encoding = Mail::Encodings.get_encoding('7bit')

  @mark_for_delete = false

  if args.flatten.first.respond_to?(:each_pair)
    init_with_hash(args.flatten.first)
  else
    init_with_string(args.flatten[0].to_s)
  end

  # Support both builder styles:
  #
  #   Mail.new do
  #     to '[email protected]'
  #   end
  #
  # and
  #
  #   Mail.new do |m|
  #     m.to '[email protected]'
  #   end
  if block_given?
    if block.arity.zero?
      instance_eval(&block)
    else
      yield self
    end
  end

  self
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object

Method Missing in this implementation allows you to set any of the standard fields directly as you would the “to”, “subject” etc.

Those fields used most often (to, subject et al) are given their own method for ease of documentation and also to avoid the hook call to method missing.

This will only catch the known fields listed in:

Mail::Field::KNOWN_FIELDS

as per RFC 2822, any ruby string or method name could pretty much be a field name, so we don’t want to just catch ANYTHING sent to a message object and interpret it as a header.

This method provides all three types of header call to set, read and explicitly set with the = operator

Examples:

mail.comments = 'These are some comments'
mail.comments #=> 'These are some comments'

mail.comments 'These are other comments'
mail.comments #=> 'These are other comments'

mail.date = 'Tue, 1 Jul 2003 10:52:37 +0200'
mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'

mail.date 'Tue, 1 Jul 2003 10:52:37 +0200'
mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'

mail.resent_msg_id = '<1234@resent_msg_id.lindsaar.net>'
mail.resent_msg_id #=> '<1234@resent_msg_id.lindsaar.net>'

mail.resent_msg_id '<4567@resent_msg_id.lindsaar.net>'
mail.resent_msg_id #=> '<4567@resent_msg_id.lindsaar.net>'


1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
# File 'lib/mail/message.rb', line 1384

def method_missing(name, *args, &block)
  #:nodoc:
  # Only take the structured fields, as we could take _anything_ really
  # as it could become an optional field... "but therin lies the dark side"
  field_name = Utilities.underscoreize(name).chomp("=")
  if Mail::Field::KNOWN_FIELDS.include?(field_name)
    if args.empty?
      header[field_name]
    else
      header[field_name] = args.first
    end
  else
    super # otherwise pass it on
  end
  #:startdoc:
end

Instance Attribute Details

#delivery_handlerObject

If you assign a delivery handler, mail will call :deliver_mail on the object you assign to delivery_handler, it will pass itself as the single argument.

If you define a delivery_handler, then you are responsible for the following actions in the delivery cycle:

  • Appending the mail object to Mail.deliveries as you see fit.

  • Checking the mail.perform_deliveries flag to decide if you should actually call :deliver! the mail object or not.

  • Checking the mail.raise_delivery_errors flag to decide if you should raise delivery errors if they occur.

  • Actually calling :deliver! (with the bang) on the mail object to get it to deliver itself.

A simplest implementation of a delivery_handler would be

class MyObject

  def initialize
    @mail = Mail.new('To: [email protected]')
    @mail.delivery_handler = self
  end

  attr_accessor :mail

  def deliver_mail(mail)
    yield
  end
end

Then doing:

obj = MyObject.new
obj.mail.deliver

Would cause Mail to call obj.deliver_mail passing itself as a parameter, which then can just yield and let Mail do its own private do_delivery method.



199
200
201
# File 'lib/mail/message.rb', line 199

def delivery_handler
  @delivery_handler
end

#perform_deliveriesObject

If set to false, mail will go through the motions of doing a delivery, but not actually call the delivery method or append the mail object to the Mail.deliveries collection. Useful for testing.

Mail.deliveries.size #=> 0
mail.delivery_method :smtp
mail.perform_deliveries = false
mail.deliver                        # Mail::SMTP not called here
Mail.deliveries.size #=> 0

If you want to test and query the Mail.deliveries collection to see what mail you sent, you should set perform_deliveries to true and use the :test mail delivery_method:

Mail.deliveries.size #=> 0
mail.delivery_method :test
mail.perform_deliveries = true
mail.deliver
Mail.deliveries.size #=> 1

This setting is ignored by mail (though still available as a flag) if you define a delivery_handler



223
224
225
# File 'lib/mail/message.rb', line 223

def perform_deliveries
  @perform_deliveries
end

#raise_delivery_errorsObject

If set to false, mail will silently catch and ignore any exceptions raised through attempting to deliver an email.

This setting is ignored by mail (though still available as a flag) if you define a delivery_handler



230
231
232
# File 'lib/mail/message.rb', line 230

def raise_delivery_errors
  @raise_delivery_errors
end

Class Method Details

.default_charsetObject



232
# File 'lib/mail/message.rb', line 232

def self.default_charset; @@default_charset; end

.default_charset=(charset) ⇒ Object



233
# File 'lib/mail/message.rb', line 233

def self.default_charset=(charset); @@default_charset = charset; end

.from_hash(hash) ⇒ Object



1872
1873
1874
# File 'lib/mail/message.rb', line 1872

def self.from_hash(hash)
  Mail::Message.new(hash)
end

.from_yaml(str) ⇒ Object



1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
# File 'lib/mail/message.rb', line 1850

def self.from_yaml(str)
  hash = Mail::YAML.load(str)
  m = self.new(:headers => hash['headers'])
  hash.delete('headers')
  hash.each do |k,v|
    case
    when k == 'delivery_handler'
      begin
        m.delivery_handler = Object.const_get(v) unless Utilities.blank?(v)
      rescue NameError
      end
    when k == 'transport_encoding'
      m.transport_encoding(v)
    when k == 'multipart_body'
      v.map {|part| m.add_part Mail::Part.from_yaml(part) }
    when k.start_with?('@')
      m.instance_variable_set(k.to_sym, v)
    end
  end
  m
end

Instance Method Details

#<=>(other) ⇒ Object

Provides the operator needed for sort et al.

Compares this mail object with another mail object, this is done by date, so an email that is older than another will appear first.

Example:

mail1 = Mail.new do
  date(Time.now)
end
mail2 = Mail.new do
  date(Time.now - 86400) # 1 day older
end
[mail2, mail1].sort #=> [mail2, mail1]


334
335
336
337
338
339
340
# File 'lib/mail/message.rb', line 334

def <=>(other)
  if other.nil?
    1
  else
    self.date <=> other.date
  end
end

#==(other) ⇒ Object

Two emails are the same if they have the same fields and body contents. One gotcha here is that Mail will insert Message-IDs when calling encoded, so doing mail1.encoded == mail2.encoded is most probably not going to return what you think as the assigned Message-IDs by Mail (if not already defined as the same) will ensure that the two objects are unique, and this comparison will ALWAYS return false.

So the == operator has been defined like so: Two messages are the same if they have the same content, ignoring the Message-ID field, unless BOTH emails have a defined and different Message-ID value, then they are false.

Note that Mail creates Date and Mime-Type fields if they don’t exist. The Date field is derived from the current time, so this needs to be allowed for in comparisons. (Mime-type does not depend on dynamic data, so cannot affect equality)

So, in practice the == operator works like this:

m1 = Mail.new("Subject: Hello\r\n\r\nHello")
m2 = Mail.new("Subject: Hello\r\n\r\nHello")
m1 == m2 #=> true

m1 = Mail.new("Subject: Hello\r\n\r\nHello")
m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
m1 == m2 #=> true

m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
m2 = Mail.new("Subject: Hello\r\n\r\nHello")
m1 == m2 #=> true

m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
m1 == m2 #=> true

m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
m2 = Mail.new("Message-ID: <DIFFERENT@test>\r\nSubject: Hello\r\n\r\nHello")
m1 == m2 #=> false


377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/mail/message.rb', line 377

def ==(other) # TODO could be more efficient
  return false unless other.respond_to?(:encoded)

  stamp = Mail::CommonDateField.normalize_datetime('')
  # Note: must always dup the inputs so they are not altered by encoded
  if self.message_id && other.message_id
    dup.tap { |m| m.date ||= stamp }.encoded ==
      other.dup.tap { |m| m.date ||= stamp }.encoded
  else
    dup.tap { |m| m.message_id = '<temp@test>'; m.date ||= stamp }.encoded ==
      other.dup.tap { |m| m.message_id = '<temp@test>'; m.date ||= stamp }.encoded
  end
end

#[](name) ⇒ Object

Allows you to read an arbitrary header

Example:

mail['foo'] = '1234'
mail['foo'].to_s #=> '1234'


1341
1342
1343
# File 'lib/mail/message.rb', line 1341

def [](name)
  header[Utilities.underscoreize(name)]
end

#[]=(name, value) ⇒ Object

Allows you to add an arbitrary header

Example:

mail['foo'] = '1234'
mail['foo'].to_s #=> '1234'


1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
# File 'lib/mail/message.rb', line 1323

def []=(name, value)
  if name.to_s == 'body'
    self.body = value
  elsif /content[-_]type/i.match?(name.to_s)
    header[name] = value
  elsif name.to_s == 'charset'
    self.charset = value
  else
    header[name] = value
  end
end

#actionObject



1565
1566
1567
# File 'lib/mail/message.rb', line 1565

def action
  delivery_status_part and delivery_status_part.action
end

#add_charsetObject

Adds a content type and charset if the body is US-ASCII

Otherwise raises a warning



1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
# File 'lib/mail/message.rb', line 1479

def add_charset
  if !body.empty?
    # Only give a warning if this isn't an attachment, has non US-ASCII and the user
    # has not specified an encoding explicitly.
    if @defaulted_charset && !body.raw_source.ascii_only? && !self.attachment?
      warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
      warn(warning)
    end
    if @charset
      header[:content_type].parameters['charset'] = @charset
    end
  end
end

#add_content_transfer_encodingObject

Adds a content transfer encoding



1494
1495
1496
# File 'lib/mail/message.rb', line 1494

def add_content_transfer_encoding
  header[:content_transfer_encoding] ||= body.default_encoding
end

#add_content_typeObject

Adds a content type and charset if the body is US-ASCII

Otherwise raises a warning



1472
1473
1474
# File 'lib/mail/message.rb', line 1472

def add_content_type
  header[:content_type] = 'text/plain'
end

#add_date(date_val = '') ⇒ Object

Creates a new empty Date field and inserts it in the correct order into the Header. The DateField object will automatically generate DateTime.now’s date if you try and encode it or output it to_s without specifying a date yourself.

It will preserve any date you specify if you do.



1455
1456
1457
# File 'lib/mail/message.rb', line 1455

def add_date(date_val = '')
  header['date'] = date_val
end

#add_file(values) ⇒ Object

Adds a file to the message. You have two options with this method, you can just pass in the absolute path to the file you want and Mail will read the file, get the filename from the path you pass in and guess the MIME media type, or you can pass in the filename as a string, and pass in the file content as a blob.

Example:

m = Mail.new
m.add_file('/path/to/filename.png')

m = Mail.new
m.add_file(:filename => 'filename.png', :content => File.read('/path/to/file.jpg'))

Note also that if you add a file to an existing message, Mail will convert that message to a MIME multipart email, moving whatever plain text body you had into its own text plain part.

Example:

m = Mail.new do
  body 'this is some text'
end
m.multipart? #=> false
m.add_file('/path/to/filename.png')
m.multipart? #=> true
m.parts.first.content_type.content_type #=> 'text/plain'
m.parts.last.content_type.content_type #=> 'image/png'

See also #attachments



1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
# File 'lib/mail/message.rb', line 1764

def add_file(values)
  convert_to_multipart unless self.multipart? || Utilities.blank?(self.body.decoded)
  add_multipart_mixed_header
  if values.is_a?(String)
    basename = File.basename(values)
    filedata = File.open(values, 'rb') { |f| f.read }
  else
    basename = values[:filename]
    filedata = values
  end
  self.attachments[basename] = filedata
end

#add_message_id(msg_id_val = '') ⇒ Object

Creates a new empty Message-ID field and inserts it in the correct order into the Header. The MessageIdField object will automatically generate a unique message ID if you try and encode it or output it to_s without specifying a message id.

It will preserve the message ID you specify if you do.



1445
1446
1447
# File 'lib/mail/message.rb', line 1445

def add_message_id(msg_id_val = '')
  header['message-id'] = msg_id_val
end

#add_mime_version(ver_val = '') ⇒ Object

Creates a new empty Mime Version field and inserts it in the correct order into the Header. The MimeVersion object will automatically generate set itself to ‘1.0’ if you try and encode it or output it to_s without specifying a version yourself.

It will preserve any date you specify if you do.



1465
1466
1467
# File 'lib/mail/message.rb', line 1465

def add_mime_version(ver_val = '')
  header['mime-version'] = ver_val
end

#add_part(part) ⇒ Object

Adds a part to the parts list or creates the part list



1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
# File 'lib/mail/message.rb', line 1708

def add_part(part)
  if !body.multipart? && !Utilities.blank?(self.body.decoded)
    @text_part = Mail::Part.new('Content-Type: text/plain;')
    @text_part.body = body.decoded
    self.body << @text_part
    add_multipart_alternate_header
  end
  add_boundary
  self.body << part
end

#all_partsObject



1934
1935
1936
# File 'lib/mail/message.rb', line 1934

def all_parts
  parts.map { |p| [p, p.all_parts] }.flatten
end

#attachmentObject

Returns the attachment data if there is any



1925
1926
1927
# File 'lib/mail/message.rb', line 1925

def attachment
  @attachment
end

#attachment?Boolean

Returns true if this part is an attachment, false otherwise.

Returns:

  • (Boolean)


1920
1921
1922
# File 'lib/mail/message.rb', line 1920

def attachment?
  !!find_attachment
end

#attachmentsObject

Returns an AttachmentsList object, which holds all of the attachments in the receiver object (either the entire email or a part within) and all of its descendants.

It also allows you to add attachments to the mail object directly, like so:

mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')

If you do this, then Mail will take the file name and work out the MIME media type set the Content-Type, Content-Disposition, Content-Transfer-Encoding and base64 encode the contents of the attachment all for you.

You can also specify overrides if you want by passing a hash instead of a string:

mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
                                    :content => File.read('/path/to/filename.jpg')}

If you want to use a different encoding than Base64, you can pass an encoding in, but then it is up to you to pass in the content pre-encoded, and don’t expect Mail to know how to decode this data:

file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
                                    :encoding => 'SpecialEncoding',
                                    :content => file_content }

You can also search for specific attachments:

# By Filename
mail.attachments['filename.jpg']   #=> Mail::Part object or nil

# or by index
mail.attachments[0]                #=> Mail::Part (first attachment)


1633
1634
1635
# File 'lib/mail/message.rb', line 1633

def attachments
  parts.attachments
end

#bcc(val = nil) ⇒ Object

Returns the Bcc value of the mail object as an array of strings of address specs.

Example:

mail.bcc = 'Mikel <[email protected]>'
mail.bcc #=> ['[email protected]']
mail.bcc = 'Mikel <[email protected]>, [email protected]'
mail.bcc #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.bcc 'Mikel <[email protected]>'
mail.bcc #=> ['[email protected]']

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.bcc 'Mikel <[email protected]>'
mail.bcc << '[email protected]'
mail.bcc #=> ['[email protected]', '[email protected]']


507
508
509
# File 'lib/mail/message.rb', line 507

def bcc( val = nil )
  default :bcc, val
end

#bcc=(val) ⇒ Object

Sets the Bcc value of the mail object, pass in a string of the field

Example:

mail.bcc = 'Mikel <[email protected]>'
mail.bcc #=> ['[email protected]']
mail.bcc = 'Mikel <[email protected]>, [email protected]'
mail.bcc #=> ['[email protected]', '[email protected]']


519
520
521
# File 'lib/mail/message.rb', line 519

def bcc=( val )
  header[:bcc] = val
end

#bcc_addrsObject

Returns an array of addresses (the encoded value) in the Bcc field, if no Bcc field, returns an empty array



1313
1314
1315
# File 'lib/mail/message.rb', line 1313

def bcc_addrs
  bcc ? [bcc].flatten : []
end

#body(value = nil) ⇒ Object

Returns the body of the message object. Or, if passed a parameter sets the value.

Example:

mail = Mail::Message.new('To: mikel\r\n\r\nThis is the body')
mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...

mail.body 'This is another body'
mail.body #=> #<Mail::Body:0x13919c @raw_source="This is anothe...


1258
1259
1260
1261
1262
1263
1264
1265
# File 'lib/mail/message.rb', line 1258

def body(value = nil)
  if value
    self.body = value
  else
    process_body_raw if @body_raw
    @body
  end
end

#body=(value) ⇒ Object

Sets the body object of the message object.

Example:

mail.body = 'This is the body'
mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...

You can also reset the body of an Message object by setting body to nil

Example:

mail.body = 'this is the body'
mail.body.encoded #=> 'this is the body'
mail.body = nil
mail.body.encoded #=> ''

If you try and set the body of an email that is a multipart email, then instead of deleting all the parts of your email, mail will add a text/plain part to your email:

mail.add_file 'somefilename.png'
mail.parts.length #=> 1
mail.body = "This is a body"
mail.parts.length #=> 2
mail.parts.last.content_type.content_type #=> 'This is a body'


1244
1245
1246
# File 'lib/mail/message.rb', line 1244

def body=(value)
  body_lazy(value)
end

#body_encoding(value = nil) ⇒ Object



1267
1268
1269
1270
1271
1272
1273
# File 'lib/mail/message.rb', line 1267

def body_encoding(value = nil)
  if value.nil?
    body.encoding
  else
    body.encoding = value
  end
end

#body_encoding=(value) ⇒ Object



1275
1276
1277
# File 'lib/mail/message.rb', line 1275

def body_encoding=(value)
  body.encoding = value
end

#bounced?Boolean

Returns:

  • (Boolean)


1561
1562
1563
# File 'lib/mail/message.rb', line 1561

def bounced?
  delivery_status_part and delivery_status_part.bounced?
end

#boundaryObject

Returns the current boundary for this message part



1590
1591
1592
# File 'lib/mail/message.rb', line 1590

def boundary
  content_type_parameters ? content_type_parameters['boundary'] : nil
end

#cc(val = nil) ⇒ Object

Returns the Cc value of the mail object as an array of strings of address specs.

Example:

mail.cc = 'Mikel <[email protected]>'
mail.cc #=> ['[email protected]']
mail.cc = 'Mikel <[email protected]>, [email protected]'
mail.cc #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.cc 'Mikel <[email protected]>'
mail.cc #=> ['[email protected]']

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.cc 'Mikel <[email protected]>'
mail.cc << '[email protected]'
mail.cc #=> ['[email protected]', '[email protected]']


548
549
550
# File 'lib/mail/message.rb', line 548

def cc( val = nil )
  default :cc, val
end

#cc=(val) ⇒ Object

Sets the Cc value of the mail object, pass in a string of the field

Example:

mail.cc = 'Mikel <[email protected]>'
mail.cc #=> ['[email protected]']
mail.cc = 'Mikel <[email protected]>, [email protected]'
mail.cc #=> ['[email protected]', '[email protected]']


560
561
562
# File 'lib/mail/message.rb', line 560

def cc=( val )
  header[:cc] = val
end

#cc_addrsObject

Returns an array of addresses (the encoded value) in the Cc field, if no Cc field, returns an empty array



1307
1308
1309
# File 'lib/mail/message.rb', line 1307

def cc_addrs
  cc ? [cc].flatten : []
end

#charsetObject

Returns the character set defined in the content type field



1504
1505
1506
1507
1508
1509
1510
# File 'lib/mail/message.rb', line 1504

def charset
  if @header
    has_content_type? && !multipart? ? content_type_parameters['charset'] : @charset
  else
    @charset
  end
end

#charset=(value) ⇒ Object

Sets the charset to the supplied value.



1513
1514
1515
1516
1517
# File 'lib/mail/message.rb', line 1513

def charset=(value)
  @defaulted_charset = false
  @charset = value
  @header.charset = value
end

#comments(val = nil) ⇒ Object



564
565
566
# File 'lib/mail/message.rb', line 564

def comments( val = nil )
  default :comments, val
end

#comments=(val) ⇒ Object



568
569
570
# File 'lib/mail/message.rb', line 568

def comments=( val )
  header[:comments] = val
end

#content_description(val = nil) ⇒ Object



572
573
574
# File 'lib/mail/message.rb', line 572

def content_description( val = nil )
  default :content_description, val
end

#content_description=(val) ⇒ Object



576
577
578
# File 'lib/mail/message.rb', line 576

def content_description=( val )
  header[:content_description] = val
end

#content_disposition(val = nil) ⇒ Object



580
581
582
# File 'lib/mail/message.rb', line 580

def content_disposition( val = nil )
  default :content_disposition, val
end

#content_disposition=(val) ⇒ Object



584
585
586
# File 'lib/mail/message.rb', line 584

def content_disposition=( val )
  header[:content_disposition] = val
end

#content_id(val = nil) ⇒ Object



588
589
590
# File 'lib/mail/message.rb', line 588

def content_id( val = nil )
  default :content_id, val
end

#content_id=(val) ⇒ Object



592
593
594
# File 'lib/mail/message.rb', line 592

def content_id=( val )
  header[:content_id] = val
end

#content_location(val = nil) ⇒ Object



596
597
598
# File 'lib/mail/message.rb', line 596

def content_location( val = nil )
  default :content_location, val
end

#content_location=(val) ⇒ Object



600
601
602
# File 'lib/mail/message.rb', line 600

def content_location=( val )
  header[:content_location] = val
end

#content_transfer_encoding(val = nil) ⇒ Object



604
605
606
# File 'lib/mail/message.rb', line 604

def content_transfer_encoding( val = nil )
  default :content_transfer_encoding, val
end

#content_transfer_encoding=(val) ⇒ Object



608
609
610
# File 'lib/mail/message.rb', line 608

def content_transfer_encoding=( val )
  header[:content_transfer_encoding] = val
end

#content_type(val = nil) ⇒ Object



612
613
614
# File 'lib/mail/message.rb', line 612

def content_type( val = nil )
  default :content_type, val
end

#content_type=(val) ⇒ Object



616
617
618
# File 'lib/mail/message.rb', line 616

def content_type=( val )
  header[:content_type] = val
end

#content_type_parametersObject

Returns the content type parameters



1530
1531
1532
# File 'lib/mail/message.rb', line 1530

def content_type_parameters
  has_content_type? ? header[:content_type].parameters : nil rescue nil
end

#convert_to_multipartObject



1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
# File 'lib/mail/message.rb', line 1780

def convert_to_multipart
  text_part = Mail::Part.new(:body => body.decoded)

  MULTIPART_CONVERSION_CONTENT_FIELDS.each do |field_name|
    if value = send(field_name)
      writer = :"#{field_name}="
      text_part.send writer, value
      send writer, nil
    end
  end
  text_part.charset = charset unless @defaulted_charset

  self.body = ''
  self.body << text_part
end

#date(val = nil) ⇒ Object



620
621
622
# File 'lib/mail/message.rb', line 620

def date( val = nil )
  default :date, val
end

#date=(val) ⇒ Object



624
625
626
# File 'lib/mail/message.rb', line 624

def date=( val )
  header[:date] = val
end

#decode_bodyObject



1914
1915
1916
# File 'lib/mail/message.rb', line 1914

def decode_body
  body.decoded
end

#decodedObject



1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
# File 'lib/mail/message.rb', line 1893

def decoded
  case
  when self.text?
    decode_body_as_text
  when self.attachment?
    decode_body
  when !self.multipart?
    body.decoded
  else
    raise NoMethodError, 'This message cannot be decoded as _entire_ message, try calling #decoded on the various fields and body or parts if it is a multipart message.'
  end
end

#default(sym, val = nil) ⇒ Object

Returns the default value of the field requested as a symbol.

Each header field has a :default method which returns the most common use case for that field, for example, the date field types will return a DateTime object when sent :default, the subject, or unstructured fields will return a decoded string of their value, the address field types will return a single addr_spec or an array of addr_specs if there is more than one.



1211
1212
1213
1214
1215
1216
1217
# File 'lib/mail/message.rb', line 1211

def default( sym, val = nil )
  if val
    header[sym] = val
  elsif field = header[sym]
    field.default
  end
end

#deliverObject

Delivers a mail object.

Examples:

mail = Mail.read('file.eml')
mail.deliver


250
251
252
253
254
255
256
257
258
259
# File 'lib/mail/message.rb', line 250

def deliver
  inform_interceptors
  if delivery_handler
    delivery_handler.deliver_mail(self) { do_delivery }
  else
    do_delivery
  end
  inform_observers
  self
end

#deliver!Object

This method bypasses checking perform_deliveries and raise_delivery_errors, so use with caution.

It still however fires off the interceptors and calls the observers callbacks if they are defined.

Returns self



267
268
269
270
271
272
# File 'lib/mail/message.rb', line 267

def deliver!
  inform_interceptors
  response = delivery_method.deliver!(self)
  inform_observers
  delivery_method.settings[:return_response] ? response : self
end

#delivery_method(method = nil, settings = {}) ⇒ Object



274
275
276
277
278
279
280
# File 'lib/mail/message.rb', line 274

def delivery_method(method = nil, settings = {})
  unless method
    @delivery_method
  else
    @delivery_method = Configuration.instance.lookup_delivery_method(method).new(settings)
  end
end

#delivery_status_partObject

returns the part in a multipart/report email that has the content-type delivery-status



1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
# File 'lib/mail/message.rb', line 1550

def delivery_status_part
  unless defined? @delivery_status_part
    @delivery_status_part =
      if delivery_status_report?
        parts.detect(&:delivery_status_report_part?)
      end
  end

  @delivery_status_part
end

#delivery_status_report?Boolean

Returns true if the message is a multipart/report; report-type=delivery-status;

Returns:

  • (Boolean)


1545
1546
1547
# File 'lib/mail/message.rb', line 1545

def delivery_status_report?
  multipart_report? && /^delivery-status$/i.match?(content_type_parameters['report-type'])
end

#destinationsObject

Returns the list of addresses this message should be sent to by collecting the addresses off the to, cc and bcc fields.

Example:

mail.to = '[email protected]'
mail.cc = '[email protected]'
mail.bcc = '[email protected]'
mail.destinations.length #=> 3
mail.destinations.first #=> '[email protected]'


1289
1290
1291
# File 'lib/mail/message.rb', line 1289

def destinations
  [to_addrs, cc_addrs, bcc_addrs].compact.flatten
end

#diagnostic_codeObject



1577
1578
1579
# File 'lib/mail/message.rb', line 1577

def diagnostic_code
  delivery_status_part and delivery_status_part.diagnostic_code
end

#encodedObject

Outputs an encoded string representation of the mail message including all headers, attachments, etc. This is an encoded email in US-ASCII, so it is able to be directly sent to an email server.



1810
1811
1812
1813
1814
1815
1816
# File 'lib/mail/message.rb', line 1810

def encoded
  ready_to_send!
  buffer = header.encoded
  buffer << "\r\n"
  buffer << body.encoded(content_transfer_encoding)
  buffer
end

#envelope_dateObject



425
426
427
# File 'lib/mail/message.rb', line 425

def envelope_date
  @envelope ? @envelope.date : nil
end

#envelope_fromObject



421
422
423
# File 'lib/mail/message.rb', line 421

def envelope_from
  @envelope ? @envelope.from : nil
end

#error_statusObject



1573
1574
1575
# File 'lib/mail/message.rb', line 1573

def error_status
  delivery_status_part and delivery_status_part.error_status
end

#errorsObject

Returns a list of parser errors on the header, each field that had an error will be reparsed as an unstructured field to preserve the data inside, but will not be used for further processing.

It returns a nested array of [field_name, value, original_error_message] per error found.

Example:

message = Mail.new("Content-Transfer-Encoding: weirdo\r\n")
message.errors.size #=> 1
message.errors.first[0] #=> "Content-Transfer-Encoding"
message.errors.first[1] #=> "weirdo"
message.errors.first[2] #=> <The original error message exception>

This is a good first defence on detecting spam by the way. Some spammers send invalid emails to try and get email parsers to give up parsing them.



478
479
480
# File 'lib/mail/message.rb', line 478

def errors
  header.errors
end

#filenameObject

Returns the filename of the attachment



1930
1931
1932
# File 'lib/mail/message.rb', line 1930

def filename
  find_attachment
end

#final_recipientObject



1569
1570
1571
# File 'lib/mail/message.rb', line 1569

def final_recipient
  delivery_status_part and delivery_status_part.final_recipient
end

#find_first_mime_type(mt) ⇒ Object



1938
1939
1940
# File 'lib/mail/message.rb', line 1938

def find_first_mime_type(mt)
  all_parts.detect { |p| p.mime_type == mt && !p.attachment? }
end

#from(val = nil) ⇒ Object

Returns the From value of the mail object as an array of strings of address specs.

Example:

mail.from = 'Mikel <[email protected]>'
mail.from #=> ['[email protected]']
mail.from = 'Mikel <[email protected]>, [email protected]'
mail.from #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.from 'Mikel <[email protected]>'
mail.from #=> ['[email protected]']

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.from 'Mikel <[email protected]>'
mail.from << '[email protected]'
mail.from #=> ['[email protected]', '[email protected]']


665
666
667
# File 'lib/mail/message.rb', line 665

def from( val = nil )
  default :from, val
end

#from=(val) ⇒ Object

Sets the From value of the mail object, pass in a string of the field

Example:

mail.from = 'Mikel <[email protected]>'
mail.from #=> ['[email protected]']
mail.from = 'Mikel <[email protected]>, [email protected]'
mail.from #=> ['[email protected]', '[email protected]']


677
678
679
# File 'lib/mail/message.rb', line 677

def from=( val )
  header[:from] = val
end

#from_addrsObject

Returns an array of addresses (the encoded value) in the From field, if no From field, returns an empty array



1295
1296
1297
# File 'lib/mail/message.rb', line 1295

def from_addrs
  from ? [from].flatten : []
end

#has_attachments?Boolean

Returns:

  • (Boolean)


1637
1638
1639
# File 'lib/mail/message.rb', line 1637

def has_attachments?
  !attachments.empty?
end

#has_charset?Boolean

Returns:

  • (Boolean)


1430
1431
1432
1433
# File 'lib/mail/message.rb', line 1430

def has_charset?
  tmp = header[:content_type].parameters rescue nil
  !!(has_content_type? && tmp && tmp['charset'])
end

#has_content_transfer_encoding?Boolean

Returns:

  • (Boolean)


1435
1436
1437
# File 'lib/mail/message.rb', line 1435

def has_content_transfer_encoding?
  header[:content_transfer_encoding] && Utilities.blank?(header[:content_transfer_encoding].errors)
end

#has_content_type?Boolean

Returns:

  • (Boolean)


1425
1426
1427
1428
# File 'lib/mail/message.rb', line 1425

def has_content_type?
  tmp = header[:content_type].main_type rescue nil
  !!tmp
end

#has_date?Boolean

Returns true if the message has a Date field, the field may or may not have a value, but the field exists or not.

Returns:

  • (Boolean)


1415
1416
1417
# File 'lib/mail/message.rb', line 1415

def has_date?
  header.has_date?
end

#has_message_id?Boolean

Returns true if the message has a message ID field, the field may or may not have a value, but the field exists or not.

Returns:

  • (Boolean)


1409
1410
1411
# File 'lib/mail/message.rb', line 1409

def has_message_id?
  header.has_message_id?
end

#has_mime_version?Boolean

Returns true if the message has a MIME-Version field, the field may or may not have a value, but the field exists or not.

Returns:

  • (Boolean)


1421
1422
1423
# File 'lib/mail/message.rb', line 1421

def has_mime_version?
  header.has_mime_version?
end

#header(value = nil) ⇒ Object

Returns the header object of the message object. Or, if passed a parameter sets the value.

Example:

mail = Mail::Message.new('To: mikel\r\nFrom: you')
mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...

mail.header #=> nil
mail.header 'To: mikel\r\nFrom: you'
mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...


450
451
452
# File 'lib/mail/message.rb', line 450

def header(value = nil)
  value ? self.header = value : @header
end

#header=(value) ⇒ Object

Sets the header of the message object.

Example:

mail.header = 'To: [email protected]\r\nFrom: [email protected]'
mail.header #=> <#Mail::Header


435
436
437
# File 'lib/mail/message.rb', line 435

def header=(value)
  @header = Mail::Header.new(value, charset)
end

#header_fieldsObject

Returns an FieldList of all the fields in the header in the order that they appear in the header



1403
1404
1405
# File 'lib/mail/message.rb', line 1403

def header_fields
  header.fields
end

#headers(hash = {}) ⇒ Object

Provides a way to set custom headers, by passing in a hash



455
456
457
458
459
# File 'lib/mail/message.rb', line 455

def headers(hash = {})
  hash.each_pair do |k,v|
    header[k] = v
  end
end

#html_part(&block) ⇒ Object

Accessor for html_part



1642
1643
1644
1645
1646
1647
1648
# File 'lib/mail/message.rb', line 1642

def html_part(&block)
  if block_given?
    self.html_part = Mail::Part.new(:content_type => 'text/html', &block)
  else
    @html_part || find_first_mime_type('text/html')
  end
end

#html_part=(msg) ⇒ Object

Helper to add a html part to a multipart/alternative email. If this and text_part are both defined in a message, then it will be a multipart/alternative message and set itself that way.



1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
# File 'lib/mail/message.rb', line 1662

def html_part=(msg)
  # Assign the html part and set multipart/alternative if there's a text part.
  if msg
    msg = Mail::Part.new(:body => msg) unless msg.kind_of?(Mail::Message)

    @html_part = msg
    @html_part.content_type = 'text/html' unless @html_part.has_content_type?
    add_multipart_alternate_header if text_part
    add_part @html_part

  # If nil, delete the html part and back out of multipart/alternative.
  elsif @html_part
    parts.delete_if { |p| p.object_id == @html_part.object_id }
    @html_part = nil
    if text_part
      self.content_type = nil
      body.boundary = nil
    end
  end
end

#in_reply_to(val = nil) ⇒ Object



681
682
683
# File 'lib/mail/message.rb', line 681

def in_reply_to( val = nil )
  default :in_reply_to, val
end

#in_reply_to=(val) ⇒ Object



685
686
687
# File 'lib/mail/message.rb', line 685

def in_reply_to=( val )
  header[:in_reply_to] = val
end

#inform_interceptorsObject



240
241
242
# File 'lib/mail/message.rb', line 240

def inform_interceptors
  Mail.inform_interceptors(self)
end

#inform_observersObject



236
237
238
# File 'lib/mail/message.rb', line 236

def inform_observers
  Mail.inform_observers(self)
end

#initialize_copy(original) ⇒ Object



391
392
393
394
# File 'lib/mail/message.rb', line 391

def initialize_copy(original)
  super
  @header = @header.dup
end

#inspectObject



1880
1881
1882
# File 'lib/mail/message.rb', line 1880

def inspect
  "#<#{self.class}:#{self.object_id}, Multipart: #{multipart?}, Headers: #{header.field_summary}>"
end

#inspect_structureObject



1884
1885
1886
1887
1888
1889
1890
1891
# File 'lib/mail/message.rb', line 1884

def inspect_structure
  inspect +
  if self.multipart?
    "\n" + parts.inspect_structure
  else
    ''
  end
end

#is_marked_for_delete?Boolean

Returns whether message will be marked for deletion. If so, the message will be deleted at session close (i.e. after #find exits), but only if also using the #find_and_delete method, or by calling #find with :delete_after_find set to true.

Side-note: Just to be clear, this method will return true even if the message hasn’t yet been marked for delete on the mail server. However, if this method returns true, it *will be* marked on the server after each block yields back to #find or #find_and_delete.

Returns:

  • (Boolean)


1967
1968
1969
# File 'lib/mail/message.rb', line 1967

def is_marked_for_delete?
  return @mark_for_delete
end

#keywords(val = nil) ⇒ Object



689
690
691
# File 'lib/mail/message.rb', line 689

def keywords( val = nil )
  default :keywords, val
end

#keywords=(val) ⇒ Object



693
694
695
# File 'lib/mail/message.rb', line 693

def keywords=( val )
  header[:keywords] = val
end

#main_typeObject

Returns the main content type



1520
1521
1522
# File 'lib/mail/message.rb', line 1520

def main_type
  has_content_type? ? header[:content_type].main_type : nil rescue nil
end

#mark_for_delete=(value = true) ⇒ Object

Sets whether this message should be deleted at session close (i.e. after #find). Message will only be deleted if messages are retrieved using the #find_and_delete method, or by calling #find with :delete_after_find set to true.



1954
1955
1956
# File 'lib/mail/message.rb', line 1954

def mark_for_delete=(value = true)
  @mark_for_delete = value
end

#message_id(val = nil) ⇒ Object

Returns the Message-ID of the mail object. Note, per RFC 2822 the Message ID consists of what is INSIDE the < > usually seen in the mail header, so this method will return only what is inside.

Example:

mail.message_id = '<[email protected]>'
mail.message_id #=> '[email protected]'

Also allows you to set the Message-ID by passing a string as a parameter

mail.message_id '<[email protected]>'
mail.message_id #=> '[email protected]'


710
711
712
# File 'lib/mail/message.rb', line 710

def message_id( val = nil )
  default :message_id, val
end

#message_id=(val) ⇒ Object

Sets the Message-ID. Note, per RFC 2822 the Message ID consists of what is INSIDE the < > usually seen in the mail header, so this method will return only what is inside.

mail.message_id = '<[email protected]>'
mail.message_id #=> '[email protected]'


719
720
721
# File 'lib/mail/message.rb', line 719

def message_id=( val )
  header[:message_id] = val
end

#mime_typeObject

Returns the MIME media type of part we are on, this is taken from the content-type header



1499
1500
1501
# File 'lib/mail/message.rb', line 1499

def mime_type
  has_content_type? ? header[:content_type].string : nil rescue nil
end

#mime_version(val = nil) ⇒ Object

Returns the MIME version of the email as a string

Example:

mail.mime_version = '1.0'
mail.mime_version #=> '1.0'

Also allows you to set the MIME version by passing a string as a parameter.

Example:

mail.mime_version '1.0'
mail.mime_version #=> '1.0'


736
737
738
# File 'lib/mail/message.rb', line 736

def mime_version( val = nil )
  default :mime_version, val
end

#mime_version=(val) ⇒ Object

Sets the MIME version of the email by accepting a string

Example:

mail.mime_version = '1.0'
mail.mime_version #=> '1.0'


746
747
748
# File 'lib/mail/message.rb', line 746

def mime_version=( val )
  header[:mime_version] = val
end

#multipart?Boolean

Returns true if the message is multipart

Returns:

  • (Boolean)


1535
1536
1537
# File 'lib/mail/message.rb', line 1535

def multipart?
  has_content_type? ? /^multipart$/i.match?(main_type) : false
end

#multipart_report?Boolean

Returns true if the message is a multipart/report

Returns:

  • (Boolean)


1540
1541
1542
# File 'lib/mail/message.rb', line 1540

def multipart_report?
  multipart? && /^report$/i.match?(sub_type)
end

#part(params = {}) {|new_part| ... } ⇒ Object

Allows you to add a part in block form to an existing mail message object

Example:

mail = Mail.new do
  part :content_type => "multipart/alternative", :content_disposition => "inline" do |p|
    p.part :content_type => "text/plain", :body => "test text\nline #2"
    p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
  end
end

Yields:

  • (new_part)


1729
1730
1731
1732
1733
# File 'lib/mail/message.rb', line 1729

def part(params = {})
  new_part = Part.new(params)
  yield new_part if block_given?
  add_part(new_part)
end

#partsObject

Returns a parts list object of all the parts in the message



1595
1596
1597
# File 'lib/mail/message.rb', line 1595

def parts
  body.parts
end

#raw_envelopeObject

The raw_envelope is the From [email protected] Mon May 2 16:07:05 2009 type field that you can see at the top of any email that has come from a mailbox



417
418
419
# File 'lib/mail/message.rb', line 417

def raw_envelope
  @raw_envelope
end

#raw_sourceObject

Provides access to the raw source of the message as it was when it was instantiated. This is set at initialization and so is untouched by the parsers or decoder / encoders

Example:

mail = Mail.new('This is an invalid email message')
mail.raw_source #=> "This is an invalid email message"


404
405
406
# File 'lib/mail/message.rb', line 404

def raw_source
  @raw_source
end

#readObject



1906
1907
1908
1909
1910
1911
1912
# File 'lib/mail/message.rb', line 1906

def read
  if self.attachment?
    decode_body
  else
    raise NoMethodError, 'Can not call read on a part unless it is an attachment.'
  end
end

#ready_to_send!Object

Encodes the message, calls encode on all its parts, gets an email message ready to send



1798
1799
1800
1801
1802
1803
1804
1805
# File 'lib/mail/message.rb', line 1798

def ready_to_send!
  identify_and_set_transfer_encoding
  parts.each do |part|
    part.transport_encoding = transport_encoding
    part.ready_to_send!
  end
  add_required_fields
end

#received(val = nil) ⇒ Object



750
751
752
753
754
755
756
# File 'lib/mail/message.rb', line 750

def received( val = nil )
  if val
    header[:received] = val
  else
    header[:received]
  end
end

#received=(val) ⇒ Object



758
759
760
# File 'lib/mail/message.rb', line 758

def received=( val )
  header[:received] = val
end

#references(val = nil) ⇒ Object



762
763
764
# File 'lib/mail/message.rb', line 762

def references( val = nil )
  default :references, val
end

#references=(val) ⇒ Object



766
767
768
# File 'lib/mail/message.rb', line 766

def references=( val )
  header[:references] = val
end

#remote_mtaObject



1581
1582
1583
# File 'lib/mail/message.rb', line 1581

def remote_mta
  delivery_status_part and delivery_status_part.remote_mta
end

#reply(*args, &block) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/mail/message.rb', line 282

def reply(*args, &block)
  self.class.new.tap do |reply|
    if message_id
      bracketed_message_id = "<#{message_id}>"
      reply.in_reply_to = bracketed_message_id
      if !references.nil?
        refs = [references].flatten.map { |r| "<#{r}>" }
        refs << bracketed_message_id
        reply.references = refs.join(' ')
      elsif !in_reply_to.nil? && !in_reply_to.kind_of?(Array)
        reply.references = "<#{in_reply_to}> #{bracketed_message_id}"
      end
      reply.references ||= bracketed_message_id
    end
    if subject
      reply.subject = /^Re:/i.match?(subject) ? subject : "Re: #{subject}"
    end
    if reply_to || from
      reply.to = self[reply_to ? :reply_to : :from].to_s
    end
    if to
      reply.from = self[:to].formatted.first.to_s
    end

    unless args.empty?
      if args.flatten.first.respond_to?(:each_pair)
        reply.send(:init_with_hash, args.flatten.first)
      else
        reply.send(:init_with_string, args.flatten[0].to_s.strip)
      end
    end

    if block_given?
      reply.instance_eval(&block)
    end
  end
end

#reply_to(val = nil) ⇒ Object

Returns the Reply-To value of the mail object as an array of strings of address specs.

Example:

mail.reply_to = 'Mikel <[email protected]>'
mail.reply_to #=> ['[email protected]']
mail.reply_to = 'Mikel <[email protected]>, [email protected]'
mail.reply_to #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.reply_to 'Mikel <[email protected]>'
mail.reply_to #=> ['[email protected]']

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.reply_to 'Mikel <[email protected]>'
mail.reply_to << '[email protected]'
mail.reply_to #=> ['[email protected]', '[email protected]']


795
796
797
# File 'lib/mail/message.rb', line 795

def reply_to( val = nil )
  default :reply_to, val
end

#reply_to=(val) ⇒ Object

Sets the Reply-To value of the mail object, pass in a string of the field

Example:

mail.reply_to = 'Mikel <[email protected]>'
mail.reply_to #=> ['[email protected]']
mail.reply_to = 'Mikel <[email protected]>, [email protected]'
mail.reply_to #=> ['[email protected]', '[email protected]']


807
808
809
# File 'lib/mail/message.rb', line 807

def reply_to=( val )
  header[:reply_to] = val
end

#resent_bcc(val = nil) ⇒ Object

Returns the Resent-Bcc value of the mail object as an array of strings of address specs.

Example:

mail.resent_bcc = 'Mikel <[email protected]>'
mail.resent_bcc #=> ['[email protected]']
mail.resent_bcc = 'Mikel <[email protected]>, [email protected]'
mail.resent_bcc #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.resent_bcc 'Mikel <[email protected]>'
mail.resent_bcc #=> ['[email protected]']

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.resent_bcc 'Mikel <[email protected]>'
mail.resent_bcc << '[email protected]'
mail.resent_bcc #=> ['[email protected]', '[email protected]']


836
837
838
# File 'lib/mail/message.rb', line 836

def resent_bcc( val = nil )
  default :resent_bcc, val
end

#resent_bcc=(val) ⇒ Object

Sets the Resent-Bcc value of the mail object, pass in a string of the field

Example:

mail.resent_bcc = 'Mikel <[email protected]>'
mail.resent_bcc #=> ['[email protected]']
mail.resent_bcc = 'Mikel <[email protected]>, [email protected]'
mail.resent_bcc #=> ['[email protected]', '[email protected]']


848
849
850
# File 'lib/mail/message.rb', line 848

def resent_bcc=( val )
  header[:resent_bcc] = val
end

#resent_cc(val = nil) ⇒ Object

Returns the Resent-Cc value of the mail object as an array of strings of address specs.

Example:

mail.resent_cc = 'Mikel <[email protected]>'
mail.resent_cc #=> ['[email protected]']
mail.resent_cc = 'Mikel <[email protected]>, [email protected]'
mail.resent_cc #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.resent_cc 'Mikel <[email protected]>'
mail.resent_cc #=> ['[email protected]']

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.resent_cc 'Mikel <[email protected]>'
mail.resent_cc << '[email protected]'
mail.resent_cc #=> ['[email protected]', '[email protected]']


877
878
879
# File 'lib/mail/message.rb', line 877

def resent_cc( val = nil )
  default :resent_cc, val
end

#resent_cc=(val) ⇒ Object

Sets the Resent-Cc value of the mail object, pass in a string of the field

Example:

mail.resent_cc = 'Mikel <[email protected]>'
mail.resent_cc #=> ['[email protected]']
mail.resent_cc = 'Mikel <[email protected]>, [email protected]'
mail.resent_cc #=> ['[email protected]', '[email protected]']


889
890
891
# File 'lib/mail/message.rb', line 889

def resent_cc=( val )
  header[:resent_cc] = val
end

#resent_date(val = nil) ⇒ Object



893
894
895
# File 'lib/mail/message.rb', line 893

def resent_date( val = nil )
  default :resent_date, val
end

#resent_date=(val) ⇒ Object



897
898
899
# File 'lib/mail/message.rb', line 897

def resent_date=( val )
  header[:resent_date] = val
end

#resent_from(val = nil) ⇒ Object

Returns the Resent-From value of the mail object as an array of strings of address specs.

Example:

mail.resent_from = 'Mikel <[email protected]>'
mail.resent_from #=> ['[email protected]']
mail.resent_from = 'Mikel <[email protected]>, [email protected]'
mail.resent_from #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.resent_from ['Mikel <[email protected]>']
mail.resent_from #=> '[email protected]'

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.resent_from 'Mikel <[email protected]>'
mail.resent_from << '[email protected]'
mail.resent_from #=> ['[email protected]', '[email protected]']


926
927
928
# File 'lib/mail/message.rb', line 926

def resent_from( val = nil )
  default :resent_from, val
end

#resent_from=(val) ⇒ Object

Sets the Resent-From value of the mail object, pass in a string of the field

Example:

mail.resent_from = 'Mikel <[email protected]>'
mail.resent_from #=> ['[email protected]']
mail.resent_from = 'Mikel <[email protected]>, [email protected]'
mail.resent_from #=> ['[email protected]', '[email protected]']


938
939
940
# File 'lib/mail/message.rb', line 938

def resent_from=( val )
  header[:resent_from] = val
end

#resent_message_id(val = nil) ⇒ Object



942
943
944
# File 'lib/mail/message.rb', line 942

def resent_message_id( val = nil )
  default :resent_message_id, val
end

#resent_message_id=(val) ⇒ Object



946
947
948
# File 'lib/mail/message.rb', line 946

def resent_message_id=( val )
  header[:resent_message_id] = val
end

#resent_sender(val = nil) ⇒ Object

Returns the Resent-Sender value of the mail object, as a single string of an address spec. A sender per RFC 2822 must be a single address, so you can not append to this address.

Example:

mail.resent_sender = 'Mikel <[email protected]>'
mail.resent_sender #=> '[email protected]'

Also allows you to set the value by passing a value as a parameter

Example:

mail.resent_sender 'Mikel <[email protected]>'
mail.resent_sender #=> '[email protected]'


965
966
967
# File 'lib/mail/message.rb', line 965

def resent_sender( val = nil )
  default :resent_sender, val
end

#resent_sender=(val) ⇒ Object

Sets the Resent-Sender value of the mail object, pass in a string of the field

Example:

mail.resent_sender = 'Mikel <[email protected]>'
mail.resent_sender #=> '[email protected]'


975
976
977
# File 'lib/mail/message.rb', line 975

def resent_sender=( val )
  header[:resent_sender] = val
end

#resent_to(val = nil) ⇒ Object

Returns the Resent-To value of the mail object as an array of strings of address specs.

Example:

mail.resent_to = 'Mikel <[email protected]>'
mail.resent_to #=> ['[email protected]']
mail.resent_to = 'Mikel <[email protected]>, [email protected]'
mail.resent_to #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.resent_to 'Mikel <[email protected]>'
mail.resent_to #=> ['[email protected]']

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.resent_to 'Mikel <[email protected]>'
mail.resent_to << '[email protected]'
mail.resent_to #=> ['[email protected]', '[email protected]']


1004
1005
1006
# File 'lib/mail/message.rb', line 1004

def resent_to( val = nil )
  default :resent_to, val
end

#resent_to=(val) ⇒ Object

Sets the Resent-To value of the mail object, pass in a string of the field

Example:

mail.resent_to = 'Mikel <[email protected]>'
mail.resent_to #=> ['[email protected]']
mail.resent_to = 'Mikel <[email protected]>, [email protected]'
mail.resent_to #=> ['[email protected]', '[email protected]']


1016
1017
1018
# File 'lib/mail/message.rb', line 1016

def resent_to=( val )
  header[:resent_to] = val
end

#retryable?Boolean

Returns:

  • (Boolean)


1585
1586
1587
# File 'lib/mail/message.rb', line 1585

def retryable?
  delivery_status_part and delivery_status_part.retryable?
end

#return_path(val = nil) ⇒ Object

Returns the return path of the mail object, or sets it if you pass a string



1021
1022
1023
# File 'lib/mail/message.rb', line 1021

def return_path( val = nil )
  default :return_path, val
end

#return_path=(val) ⇒ Object

Sets the return path of the object



1026
1027
1028
# File 'lib/mail/message.rb', line 1026

def return_path=( val )
  header[:return_path] = val
end

#sender(val = nil) ⇒ Object

Returns the Sender value of the mail object, as a single string of an address spec. A sender per RFC 2822 must be a single address.

Example:

mail.sender = 'Mikel <[email protected]>'
mail.sender #=> '[email protected]'

Also allows you to set the value by passing a value as a parameter

Example:

mail.sender 'Mikel <[email protected]>'
mail.sender #=> '[email protected]'


1044
1045
1046
# File 'lib/mail/message.rb', line 1044

def sender( val = nil )
  default :sender, val
end

#sender=(val) ⇒ Object

Sets the Sender value of the mail object, pass in a string of the field

Example:

mail.sender = 'Mikel <[email protected]>'
mail.sender #=> '[email protected]'


1054
1055
1056
# File 'lib/mail/message.rb', line 1054

def sender=( val )
  header[:sender] = val
end

#set_envelope(val) ⇒ Object

Sets the envelope from for the email



409
410
411
412
# File 'lib/mail/message.rb', line 409

def set_envelope(val)
  @raw_envelope = val
  @envelope = Mail::Envelope.parse(val) rescue nil
end

#skip_deletionObject

Skips the deletion of this message. All other messages flagged for delete still will be deleted at session close (i.e. when #find exits). Only has an effect if you’re using #find_and_delete or #find with :delete_after_find set to true.



1946
1947
1948
# File 'lib/mail/message.rb', line 1946

def skip_deletion
  @mark_for_delete = false
end

#smtp_envelope_from(val = nil) ⇒ Object

Returns the SMTP Envelope From value of the mail object, as a single string of an address spec.

Defaults to Return-Path, Sender, or the first From address.

Example:

mail.smtp_envelope_from = 'Mikel <[email protected]>'
mail.smtp_envelope_from #=> '[email protected]'

Also allows you to set the value by passing a value as a parameter

Example:

mail.smtp_envelope_from 'Mikel <[email protected]>'
mail.smtp_envelope_from #=> '[email protected]'


1074
1075
1076
1077
1078
1079
1080
# File 'lib/mail/message.rb', line 1074

def smtp_envelope_from( val = nil )
  if val
    self.smtp_envelope_from = val
  else
    @smtp_envelope_from || return_path || sender || from_addrs.first
  end
end

#smtp_envelope_from=(val) ⇒ Object

Sets the From address on the SMTP Envelope.

Example:

mail.smtp_envelope_from = 'Mikel <[email protected]>'
mail.smtp_envelope_from #=> '[email protected]'


1088
1089
1090
# File 'lib/mail/message.rb', line 1088

def smtp_envelope_from=( val )
  @smtp_envelope_from = val
end

#smtp_envelope_to(val = nil) ⇒ Object

Returns the SMTP Envelope To value of the mail object.

Defaults to #destinations: To, Cc, and Bcc addresses.

Example:

mail.smtp_envelope_to = 'Mikel <[email protected]>'
mail.smtp_envelope_to #=> '[email protected]'

Also allows you to set the value by passing a value as a parameter

Example:

mail.smtp_envelope_to ['Mikel <[email protected]>', 'Lindsaar <[email protected]>']
mail.smtp_envelope_to #=> ['[email protected]', '[email protected]']


1107
1108
1109
1110
1111
1112
1113
# File 'lib/mail/message.rb', line 1107

def smtp_envelope_to( val = nil )
  if val
    self.smtp_envelope_to = val
  else
    @smtp_envelope_to || destinations
  end
end

#smtp_envelope_to=(val) ⇒ Object

Sets the To addresses on the SMTP Envelope.

Example:

mail.smtp_envelope_to = 'Mikel <[email protected]>'
mail.smtp_envelope_to #=> '[email protected]'

mail.smtp_envelope_to = ['Mikel <[email protected]>', 'Lindsaar <[email protected]>']
mail.smtp_envelope_to #=> ['[email protected]', '[email protected]']


1124
1125
1126
1127
1128
1129
1130
1131
1132
# File 'lib/mail/message.rb', line 1124

def smtp_envelope_to=( val )
  @smtp_envelope_to =
    case val
    when Array, NilClass
      val
    else
      [val]
    end
end

#sub_typeObject

Returns the sub content type



1525
1526
1527
# File 'lib/mail/message.rb', line 1525

def sub_type
  has_content_type? ? header[:content_type].sub_type : nil rescue nil
end

#subject(val = nil) ⇒ Object

Returns the decoded value of the subject field, as a single string.

Example:

mail.subject = "G'Day mate"
mail.subject #=> "G'Day mate"
mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
mail.subject #=> "This is あ string"

Also allows you to set the value by passing a value as a parameter

Example:

mail.subject "G'Day mate"
mail.subject #=> "G'Day mate"


1149
1150
1151
# File 'lib/mail/message.rb', line 1149

def subject( val = nil )
  default :subject, val
end

#subject=(val) ⇒ Object

Sets the Subject value of the mail object, pass in a string of the field

Example:

mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
mail.subject #=> "This is あ string"


1159
1160
1161
# File 'lib/mail/message.rb', line 1159

def subject=( val )
  header[:subject] = val
end

#text?Boolean

Returns:

  • (Boolean)


1971
1972
1973
# File 'lib/mail/message.rb', line 1971

def text?
  has_content_type? ? /^text$/i.match?(main_type) : false
end

#text_part(&block) ⇒ Object

Accessor for text_part



1651
1652
1653
1654
1655
1656
1657
# File 'lib/mail/message.rb', line 1651

def text_part(&block)
  if block_given?
    self.text_part = Mail::Part.new(:content_type => 'text/plain', &block)
  else
    @text_part || find_first_mime_type('text/plain')
  end
end

#text_part=(msg) ⇒ Object

Helper to add a text part to a multipart/alternative email. If this and html_part are both defined in a message, then it will be a multipart/alternative message and set itself that way.



1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
# File 'lib/mail/message.rb', line 1686

def text_part=(msg)
  # Assign the text part and set multipart/alternative if there's an html part.
  if msg
    msg = Mail::Part.new(:body => msg) unless msg.kind_of?(Mail::Message)

    @text_part = msg
    @text_part.content_type = 'text/plain' unless @text_part.has_content_type?
    add_multipart_alternate_header if html_part
    add_part @text_part

  # If nil, delete the text part and back out of multipart/alternative.
  elsif @text_part
    parts.delete_if { |p| p.object_id == @text_part.object_id }
    @text_part = nil
    if html_part
      self.content_type = nil
      body.boundary = nil
    end
  end
end

#to(val = nil) ⇒ Object

Returns the To value of the mail object as an array of strings of address specs.

Example:

mail.to = 'Mikel <[email protected]>'
mail.to #=> ['[email protected]']
mail.to = 'Mikel <[email protected]>, [email protected]'
mail.to #=> ['[email protected]', '[email protected]']

Also allows you to set the value by passing a value as a parameter

Example:

mail.to 'Mikel <[email protected]>'
mail.to #=> ['[email protected]']

Additionally, you can append new addresses to the returned Array like object.

Example:

mail.to 'Mikel <[email protected]>'
mail.to << '[email protected]'
mail.to #=> ['[email protected]', '[email protected]']


1188
1189
1190
# File 'lib/mail/message.rb', line 1188

def to( val = nil )
  default :to, val
end

#to=(val) ⇒ Object

Sets the To value of the mail object, pass in a string of the field

Example:

mail.to = 'Mikel <[email protected]>'
mail.to #=> ['[email protected]']
mail.to = 'Mikel <[email protected]>, [email protected]'
mail.to #=> ['[email protected]', '[email protected]']


1200
1201
1202
# File 'lib/mail/message.rb', line 1200

def to=( val )
  header[:to] = val
end

#to_addrsObject

Returns an array of addresses (the encoded value) in the To field, if no To field, returns an empty array



1301
1302
1303
# File 'lib/mail/message.rb', line 1301

def to_addrs
  to ? [to].flatten : []
end

#to_sObject



1876
1877
1878
# File 'lib/mail/message.rb', line 1876

def to_s
  encoded
end

#to_yaml(opts = {}) ⇒ Object



1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
# File 'lib/mail/message.rb', line 1830

def to_yaml(opts = {})
  hash = {}
  hash['headers'] = {}
  header.fields.each do |field|
    hash['headers'][field.name] = field.value
  end
  hash['delivery_handler'] = delivery_handler.to_s if delivery_handler
  hash['transport_encoding'] = transport_encoding.to_s
  special_variables = [:@header, :@delivery_handler, :@transport_encoding]
  if multipart?
    hash['multipart_body'] = []
    body.parts.map { |part| hash['multipart_body'] << part.to_yaml }
    special_variables.push(:@body, :@text_part, :@html_part)
  end
  (instance_variables.map(&:to_sym) - special_variables).each do |var|
    hash[var.to_s] = instance_variable_get(var)
  end
  hash.to_yaml(opts)
end

#transport_encoding(val = nil) ⇒ Object



628
629
630
631
632
633
634
# File 'lib/mail/message.rb', line 628

def transport_encoding( val = nil)
  if val
    self.transport_encoding = val
  else
    @transport_encoding
  end
end

#transport_encoding=(val) ⇒ Object



636
637
638
# File 'lib/mail/message.rb', line 636

def transport_encoding=( val )
  @transport_encoding = Mail::Encodings.get_encoding(val)
end

#without_attachments!Object



1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
# File 'lib/mail/message.rb', line 1818

def without_attachments!
  if has_attachments?
    parts.delete_attachments

    reencoded = parts.empty? ? '' : body.encoded(content_transfer_encoding)
    @body = nil # So the new parts won't be added to the existing body
    self.body = reencoded
  end

  self
end