[Tmail-talk] Adding attachments

Mikel Lindsaar raasdnil at gmail.com
Thu Jul 24 00:29:56 EDT 2008


Dear Mark,

Try setting:

mail.set_content_type 'multipart', 'mixed', {'boundary' => TMail.new_boundary}

At the top in the first 'mail' block.  You have to set the multipart
and mixed separately.  You can set the boundary to whatever you want,
but the new_boundary method is handy.

See below for the whole script.

>> multipart email with an attachment using TMail? This, incidentally, would
>> make a great section on the Getting Start pages, as it's something a lot of
>> people do.

Feel like writing one up? :)  I'll put it up if you do :)

Mikel

----------

require 'rubygems'
require 'tmail'
require 'base64'

# setup general mail settings:
mail = TMail::Mail.new
mail.mime_version = "1.0"
mail.to = "mark at mackframework.com"
mail.from = "mark at mackframework.com"
mail.reply_to = mail.from
mail.subject = "hello world"
mail.set_content_type 'multipart', 'mixed', {'boundary' => TMail.new_boundary}

# Add the text/plain portion
text = TMail::Mail.new
text.mime_version = "1.0"
text.content_type = "text/plain"
text.body = "this is my plain text email"
mail.parts << text

# Add the text/html portion
html = TMail::Mail.new
text.mime_version = "1.0"
html.content_type = "text/html"
html.body = "this is my <b>HTML</b> email"
mail.parts << html

# Add an attachment
content = File.read("/Users/mikel/Pictures/MyPicture.jpg")
attachment = TMail::Mail.new
attachment.body = Base64.encode64(content)
attachment.transfer_encoding = "Base64"
attachment.content_type = "application/octet-stream"
attachment['Content-Disposition'] = "attachment; filename=MyPicture.jpg"
mail.parts << attachment

File.open('testemail.eml', 'w') do |f|
  f.puts mail.encoded
end


More information about the Tmail-talk mailing list