| Class | TMail::Mail |
| In: |
lib/tmail/attachments.rb
lib/tmail/interface.rb lib/tmail/mail.rb lib/tmail/net.rb lib/tmail/quoting.rb |
| Parent: | Object |
Accessing a TMail object done via the TMail::Mail class. As email can be fairly complex creatures, you will find a large amount of accessor and setter methods in this class!
Most of the below methods handle the header, in fact, what TMail does best is handle the header of the email object. There are only a few methods that deal directly with the body of the email, such as base64_encode and base64_decode.
The usual way is to install the gem (see the {README}[README] on how to do this) and then put at the top of your class:
require 'tmail'
You can then create a new TMail object in your code with:
@email = TMail::Mail.new
Or if you have an email as a string, you can initialize a new TMail::Mail object and get it to parse that string for you like so:
@email = TMail::Mail.parse(email_text)
You can also read a single email off the disk, for example:
@email = TMail::Mail.load('filename.txt')
Also, you can read a mailbox (usual unix mbox format) and end up with an array of TMail objects by doing something like this:
# Note, we pass true as the last variable to open the mailbox read only
mailbox = TMail::UNIXMbox.new("mailbox", nil, true)
@emails = []
mailbox.each_port { |m| @emails << TMail::Mail.new(m) }
| ALLOW_MULTIPLE | = | { 'received' => true, 'resent-date' => true, 'resent-from' => true, 'resent-sender' => true, 'resent-to' => true, 'resent-cc' => true, 'resent-bcc' => true, 'resent-message-id' => true, 'comments' => true, 'keywords' => true | header | |
| USE_ARRAY | = | ALLOW_MULTIPLE | ||
| FIELD_ORDER | = | %w( return-path received resent-date resent-from resent-sender resent-to resent-cc resent-bcc resent-message-id date from sender reply-to to cc bcc message-id in-reply-to references subject comments keywords mime-version content-type content-transfer-encoding content-disposition content-description ) | ||
| NOSEND_FIELDS | = | %w( received bcc ) |
| load | -> | load_from |
| load | -> | loadfrom |
| body | -> | preamble |
| port | [R] |
# File lib/tmail/mail.rb, line 99 def initialize( port = nil, conf = DEFAULT_CONFIG ) @port = port || StringPort.new @config = Config.to_config(conf) @header = {} @body_port = nil @body_parsed = false @epilogue = '' @parts = [] @port.ropen {|f| parse_header f parse_body f unless @port.reproducible? } end
Returns a TMail::AddressHeader object of the field you are querying. Examples:
@mail['from'] #=> #<TMail::AddressHeader "mikel@test.com.au"> @mail['to'] #=> #<TMail::AddressHeader "mikel@test.com.au">
You can get the string value of this by passing "to_s" to the query: Example:
@mail['to'].to_s #=> "mikel@test.com.au"
# File lib/tmail/mail.rb, line 212 def []( key ) @header[key.downcase] end
Allows you to set or delete TMail header objects at will. Eamples:
@mail = TMail::Mail.new @mail['to'].to_s # => 'mikel@test.com.au' @mail['to'] = 'mikel@elsewhere.org' @mail['to'].to_s # => 'mikel@elsewhere.org' @mail.encoded # => "To: mikel@elsewhere.org\r\n\r\n" @mail['to'] = nil @mail['to'].to_s # => nil @mail.encoded # => "\r\n"
Note: setting mail[] = nil actualy deletes the header field in question from the object, it does not just set the value of the hash to nil
# File lib/tmail/mail.rb, line 235 def []=( key, val ) dkey = key.downcase if val.nil? @header.delete dkey return nil end case val when String header = new_hf(key, val) when HeaderField ; when Array ALLOW_MULTIPLE.include? dkey or raise ArgumentError, "#{key}: Header must not be multiple" @header[dkey] = val return val else header = new_hf(key, val.to_s) end if ALLOW_MULTIPLE.include? dkey (@header[dkey] ||= []).push header else @header[dkey] = header end val end
# File lib/tmail/mail.rb, line 134 def accept( strategy ) with_multipart_encoding(strategy) { ordered_each do |name, field| next if field.empty? strategy.header_name canonical(name) field.accept strategy strategy.puts end strategy.puts body_port().ropen {|r| strategy.write r.read } } end
# File lib/tmail/net.rb, line 84 def add_message_id( fqdn = nil ) self.message_id = ::TMail::new_message_id(fqdn) end
# File lib/tmail/attachments.rb, line 19 def attachment?(part) (part['content-disposition'] && part['content-disposition'].disposition == "attachment") || part.header['content-type'].main_type != "text" end
# File lib/tmail/attachments.rb, line 24 def attachments if multipart? parts.collect { |part| if part.multipart? part.attachments elsif attachment?(part) content = part.body # unquoted automatically by TMail#body file_name = (part['content-location'] && part['content-location'].body) || part.sub_header("content-type", "name") || part.sub_header("content-disposition", "filename") next if file_name.blank? || content.blank? attachment = Attachment.new(content) attachment.original_filename = file_name.strip attachment.content_type = part.content_type attachment end }.flatten.compact end end
Returns the result of decoding the TMail::Mail object body without altering the current body
# File lib/tmail/interface.rb, line 993 def base64_decode Base64.decode(self.body, @config.strict_base64decode?) end
Return the result of encoding the TMail::Mail object body without altering the current body
# File lib/tmail/interface.rb, line 978 def base64_encode Base64.folding_encode(self.body) end
Returns who the email bcc‘d as an Array of email addresses as opposed to an Array of TMail::Address objects which is what Mail#to_addrs returns
Example:
mail = TMail::Mail.new mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.bcc #=> ["mikel@me.org", "mikel@you.org"]
# File lib/tmail/interface.rb, line 292 def bcc( default = nil ) addrs2specs(bcc_addrs(nil)) || default end
Destructively sets the "Bcc:" field to the passed array of strings (which should be valid email addresses)
Example:
mail = TMail::Mail.new mail.bcc = ["mikel@abc.com", "Mikel <mikel@xyz.com>"] mail.bcc #=> ["mikel@abc.org", "mikel@xyz.org"] mail['bcc'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
# File lib/tmail/interface.rb, line 331 def bcc=( *strs ) set_string_array_attr 'Bcc', strs end
Return a TMail::Addresses instance for each entry in the "Bcc:" field of the mail object header.
If the "Bcc:" field does not exist, will return nil by default or the value you pass as the optional parameter.
Example:
mail = TMail::Mail.new mail.bcc_addrs #=> nil mail.bcc_addrs([]) #=> [] mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.bcc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
# File lib/tmail/interface.rb, line 210 def bcc_addrs( default = nil ) if h = @header['bcc'] h.addrs else default end end
Destructively set the to field of the "Bcc:" header to equal the passed in string.
TMail will parse your contents and turn each valid email address into a TMail::Address object before assigning it to the mail message.
Example:
mail = TMail::Mail.new mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.bcc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
# File lib/tmail/interface.rb, line 256 def bcc_addrs=( arg ) set_addrfield 'bcc', arg end
# File lib/tmail/quoting.rb, line 36 def body(to_charset = 'utf-8', &block) attachment_presenter = block || Proc.new { |file_name| "Attachment: #{file_name}\n" } if multipart? parts.collect { |part| header = part["content-type"] if part.multipart? part.body(to_charset, &attachment_presenter) elsif header.nil? "" elsif !attachment?(part) part.unquoted_body(to_charset) else attachment_presenter.call(header["name"] || "(unnamed)") end }.join else unquoted_body(to_charset) end end
# File lib/tmail/mail.rb, line 426 def body=( str ) # Sets the body of the email to a new (encoded) string. # # We also reparses the email if the body is ever reassigned, this is a performance hit, however when # you assign the body, you usually want to be able to make sure that you can access the attachments etc. # # Usage: # # mail.body = "Hello, this is\nthe body text" # # => "Hello, this is\nthe body" # mail.body # # => "Hello, this is\nthe body" @body_parsed = false parse_body(StringInput.new(str)) parse_body @body_port.wopen {|f| f.write str } str end
Returns who the email cc‘d as an Array of email addresses as opposed to an Array of TMail::Address objects which is what Mail#to_addrs returns
Example:
mail = TMail::Mail.new mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.cc #=> ["mikel@me.org", "mikel@you.org"]
# File lib/tmail/interface.rb, line 280 def cc( default = nil ) addrs2specs(cc_addrs(nil)) || default end
Destructively sets the "Cc:" field to the passed array of strings (which should be valid email addresses)
Example:
mail = TMail::Mail.new mail.cc = ["mikel@abc.com", "Mikel <mikel@xyz.com>"] mail.cc #=> ["mikel@abc.org", "mikel@xyz.org"] mail['cc'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
# File lib/tmail/interface.rb, line 318 def cc=( *strs ) set_string_array_attr 'Cc', strs end
Return a TMail::Addresses instance for each entry in the "Cc:" field of the mail object header.
If the "Cc:" field does not exist, will return nil by default or the value you pass as the optional parameter.
Example:
mail = TMail::Mail.new mail.cc_addrs #=> nil mail.cc_addrs([]) #=> [] mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.cc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
# File lib/tmail/interface.rb, line 190 def cc_addrs( default = nil ) if h = @header['cc'] h.addrs else default end end
Destructively set the to field of the "Cc:" header to equal the passed in string.
TMail will parse your contents and turn each valid email address into a TMail::Address object before assigning it to the mail message.
Example:
mail = TMail::Mail.new mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.cc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
# File lib/tmail/interface.rb, line 242 def cc_addrs=( arg ) set_addrfield 'cc', arg end
Returns the character set of the email. Returns nil if no encoding set or returns whatever default you pass as a parameter - note passing the parameter does NOT change the mail object in any way.
Example:
mail = TMail::Mail.load("path_to/utf8_email")
mail.charset #=> "UTF-8"
mail = TMail::Mail.new
mail.charset #=> nil
mail.charset("US-ASCII") #=> "US-ASCII"
# File lib/tmail/interface.rb, line 837 def charset( default = nil ) if h = @header['content-type'] h['charset'] or default else default end end
Destructively sets the character set used by this mail object to the passed string, you should note though that this does nothing to the mail body, just changes the header value, you will need to transliterate the body as well to match whatever you put in this header value if you are changing character sets.
Example:
mail = TMail::Mail.new mail.charset #=> nil mail.charset = "UTF-8" mail.charset #=> "UTF-8"
# File lib/tmail/interface.rb, line 856 def charset=( str ) if str if h = @header[ 'content-type' ] h['charset'] = str else store 'Content-Type', "text/plain; charset=#{str}" end end str end
Returns the current "Content-Type" of the mail instance.
If the content_type field does not exist, returns nil by default or you can pass in as the parameter for what you want the default value to be.
Example:
mail = TMail::Mail.new
mail.content_type #=> nil
mail.content_type([]) #=> []
mail = TMail::Mail.load("../test/fixtures/raw_email")
mail.content_type #=> "text/plain"
# File lib/tmail/interface.rb, line 720 def content_type( default = nil ) if h = @header['content-type'] h.content_type || default else default end end
Creates a new email in reply to self. Sets the In-Reply-To and References headers for you automagically.
Example:
mail = TMail::Mail.load("my_email")
forward_email = mail.create_forward
forward_email.class #=> TMail::Mail
forward_email.content_type #=> "multipart/mixed"
forward_email.body #=> "Attachment: (unnamed)"
forward_email.encoded #=> Returns the original email as a MIME attachment
# File lib/tmail/interface.rb, line 1085 def create_forward setup_forward create_empty_mail() end
Creates a new email in reply to self. Sets the In-Reply-To and References headers for you automagically.
Example:
mail = TMail::Mail.load("my_email")
reply_email = mail.create_reply
reply_email.class #=> TMail::Mail
reply_email.references #=> ["<d3b8cf8e49f04480850c28713a1f473e@lindsaar.net>"]
reply_email.in_reply_to #=> ["<d3b8cf8e49f04480850c28713a1f473e@lindsaar.net>"]
# File lib/tmail/interface.rb, line 1071 def create_reply setup_reply create_empty_mail() end
Returns the date of the email message as per the "date" header value or returns nil by default (if no date field exists).
You can also pass whatever default you want into this method and it will return that instead of nil if there is no date already set.
# File lib/tmail/interface.rb, line 115 def date( default = nil ) if h = @header['date'] h.date else default end end
Destructively sets the date of the mail object with the passed Time instance, returns a Time instance set to the date/time of the mail
Example:
now = Time.now mail.date = now mail.date #=> Sat Nov 03 18:47:50 +1100 2007 mail.date.class #=> Time
# File lib/tmail/interface.rb, line 132 def date=( time ) if time store 'Date', time2str(time) else @header.delete 'date' end time end
# File lib/tmail/mail.rb, line 325 def delete_if @header.delete_if do |key,val| if Array === val val.delete_if {|v| yield key, v } val.empty? else yield key, val end end end
# File lib/tmail/net.rb, line 77 def delete_no_send_fields NOSEND_FIELDS.each do |nm| delete nm end delete_if {|n,v| v.empty? } end
Returns an array of each destination in the email message including to: cc: or bcc:
Example:
mail.to = "Mikel <mikel@lindsaar.net>" mail.cc = "Trans <t@t.com>" mail.bcc = "bob <bob@me.com>" mail.destinations #=> ["mikel@lindsaar.net", "t@t.com", "bob@me.com"]
# File lib/tmail/interface.rb, line 1005 def destinations( default = nil ) ret = [] %w( to cc bcc ).each do |nm| if h = @header[nm] h.addrs.each {|i| ret.push i.address } end end ret.empty? ? default : ret end
Returns the content-disposition of the mail object, returns nil or the passed default value if given
Example:
mail = TMail::Mail.load("path_to/raw_mail_with_attachment")
mail.disposition #=> "attachment"
mail = TMail::Mail.load("path_to/plain_simple_email")
mail.disposition #=> nil
mail.disposition(false) #=> false
# File lib/tmail/interface.rb, line 918 def disposition( default = nil ) if h = @header['content-disposition'] h.disposition || default else default end end
Returns the value of a parameter in an existing content-disposition header
Example:
mail.set_disposition("attachment", {:filename => "test.rb"})
mail['content-disposition'].to_s #=> "attachment; filename=test.rb"
mail.disposition_param("filename") #=> "test.rb"
mail.disposition_param("missing_param_key") #=> nil
mail.disposition_param("missing_param_key", false) #=> false
mail.disposition_param("missing_param_key", "Nothing to see here") #=> "Nothing to see here"
# File lib/tmail/interface.rb, line 961 def disposition_param( name, default = nil ) if h = @header['content-disposition'] h[name] || default else default end end
Yields a block of destination, yielding each as a string.
(from the destinations example)
mail.each_destination { |d| puts "#{d.class}: #{d}" }
String: mikel@lindsaar.net
String: t@t.com
String: bob@me.com
# File lib/tmail/interface.rb, line 1021 def each_destination( &block ) destinations([]).each do |i| if Address === i yield i else i.each(&block) end end end
Allows you to loop through each header in the TMail::Mail object in a block Example:
@mail['to'] = 'mikel@elsewhere.org'
@mail['from'] = 'me@me.com'
@mail.each_header { |k,v| puts "#{k} = #{v}" }
# => from = me@me.com
# => to = mikel@elsewhere.org
# File lib/tmail/mail.rb, line 274 def each_header @header.each do |key, val| [val].flatten.each {|v| yield key, v } end end
Returns the "friendly" human readable part of the address
Example:
mail = TMail::Mail.new mail.from = "Mikel Lindsaar <mikel@abc.com>" mail.friendly_from #=> "Mikel Lindsaar"
# File lib/tmail/interface.rb, line 403 def friendly_from( default = nil ) h = @header['from'] a, = h.addrs return default unless a return a.phrase if a.phrase return h.comments.join(' ') unless h.comments.empty? a.spec end
Returns who the email is from as an Array of email address strings instead to an Array of TMail::Address objects which is what Mail#from_addrs returns
Example:
mail = TMail::Mail.new mail.from = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.from #=> ["mikel@me.org", "mikel@you.org"]
# File lib/tmail/interface.rb, line 379 def from( default = nil ) addrs2specs(from_addrs(nil)) || default end
Destructively sets the "From:" field to the passed array of strings (which should be valid email addresses)
Example:
mail = TMail::Mail.new mail.from = ["mikel@abc.com", "Mikel <mikel@xyz.com>"] mail.from #=> ["mikel@abc.org", "mikel@xyz.org"] mail['from'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
# File lib/tmail/interface.rb, line 392 def from=( *strs ) set_string_array_attr 'From', strs end
Return a TMail::Addresses instance for each entry in the "From:" field of the mail object header.
If the "From:" field does not exist, will return nil by default or the value you pass as the optional parameter.
Example:
mail = TMail::Mail.new mail.from_addrs #=> nil mail.from_addrs([]) #=> [] mail.from = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.from_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
# File lib/tmail/interface.rb, line 349 def from_addrs( default = nil ) if h = @header['from'] h.addrs else default end end
Destructively set the to value of the "From:" header to equal the passed in string.
TMail will parse your contents and turn each valid email address into a TMail::Address object before assigning it to the mail message.
Example:
mail = TMail::Mail.new mail.from_addrs = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>" mail.from_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
# File lib/tmail/interface.rb, line 367 def from_addrs=( arg ) set_addrfield 'from', arg end
# File lib/tmail/attachments.rb, line 15 def has_attachments? multipart? && parts.any? { |part| attachment?(part) } end
Allows you to query the mail object with a string to get the contents of the field you want.
Returns a string of the exact contnts of the field
mail.from = "mikel <mikel@lindsaar.net>"
mail.header_string("From") #=> "mikel <mikel@lindsaar.net>"
# File lib/tmail/interface.rb, line 49 def header_string( name, default = nil ) h = @header[name.downcase] or return default h.to_s end
Returns the "In-Reply-To:" field contents as an array of this mail instance if it exists
If the in_reply_to field does not exist, returns nil by default or you can pass in as the parameter for what you want the default value to be.
Example:
mail = TMail::Mail.new
mail.in_reply_to #=> nil
mail.in_reply_to([]) #=> []
TMail::Mail.load("../test/fixtures/raw_email_reply")
mail.in_reply_to #=> ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
# File lib/tmail/interface.rb, line 616 def in_reply_to( default = nil ) if h = @header['in-reply-to'] h.ids else default end end
Destructively sets the value of the "In-Reply-To:" field of an email.
Accepts an array of a single string of a message id
Example:
mail = TMail::Mail.new mail.in_reply_to = ["<348F04F142D69C21-291E56D292BC@xxxx.net>"] mail.in_reply_to #=> ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
# File lib/tmail/interface.rb, line 633 def in_reply_to=( *idstrs ) set_string_array_attr 'In-Reply-To', idstrs end
# File lib/tmail/mail.rb, line 117 def inspect "\#<#{self.class} port=#{@port.inspect} bodyport=#{@body_port.inspect}>" end
Returns the current main type of the "Content-Type" of the mail instance.
If the content_type field does not exist, returns nil by default or you can pass in as the parameter for what you want the default value to be.
Example:
mail = TMail::Mail.new
mail.main_type #=> nil
mail.main_type([]) #=> []
mail = TMail::Mail.load("../test/fixtures/raw_email")
mail.main_type #=> "text"
# File lib/tmail/interface.rb, line 740 def main_type( default = nil ) if h = @header['content-type'] h.main_type || default else default end end
Returns the message ID for this mail object instance.
If the message_id field does not exist, returns nil by default or you can pass in as the parameter for what you want the default value to be.
Example:
mail = TMail::Mail.new mail.message_id #=> nil mail.message_id(TMail.new_message_id) #=> "<47404c5326d9c_2ad4fbb80161@baci.local.tmail>" mail.message_id = TMail.new_message_id mail.message_id #=> "<47404c5326d9c_2ad4fbb80161@baci.local.tmail>"
# File lib/tmail/interface.rb, line 585 def message_id( default = nil ) if h = @header['message-id'] h.id || default else default end end
Destructively sets the message ID of the mail object instance to the passed in string
Example:
mail = TMail::Mail.new mail.message_id = "this_is_my_badly_formatted_message_id" mail.message_id #=> "this_is_my_badly_formatted_message_id"
# File lib/tmail/interface.rb, line 600 def message_id=( str ) set_string_attr 'Message-Id', str end
# File lib/tmail/net.rb, line 92 def mime_encode if parts.empty? mime_encode_singlepart else mime_encode_multipart true end end