Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending multipart mails and attachments

I am trying to send an E-Mail using the gem 'mail' with Ruby 1.9.3. It contains an text/html and an text/plain part which should be embedded as alternative parts as well an attachment.

This is my current code:

require 'mail'

mail = Mail.new
mail.delivery_method :sendmail
mail.sender = "[email protected]"
mail.to = "[email protected]"
mail.subject = "Multipart Test"
mail.content_type = "multipart/mixed"

html_part = Mail::Part.new do
  content_type 'text/html; charset=UTF-8'
  body "<h1>HTML</h1>"
end

text_part = Mail::Part.new do
  body "TEXT"
end

mail.part :content_type => "multipart/alternative" do |p|
  p.html_part = html_part
  p.text_part = text_part
end

mail.add_file :filename => "file.txt", :content => "FILE"

mail.deliver!

It results in an mail with working alternative parts but no attachment. I am using thunderbird 10.0.12 for testing.

I already posted this on github, but unfortunately the posts don't make me smarter. https://github.com/mikel/mail/issues/118#issuecomment-12276876. Maybe somebody is able to understand the last post a bit better than me ;)

Is somebody able to get this example working?

Thanks, krissi

like image 294
krissi Avatar asked Feb 21 '13 17:02

krissi


1 Answers

I managed to fix it like so:

html_part = Mail::Part.new do
  content_type  'text/html; charset=UTF-8'
  body          html
end

text_part = Mail::Part.new do
  body          text
end

mail.part :content_type => "multipart/alternative" do |p|
  p.html_part = html_part
  p.text_part = text_part
end


mail.attachments['some.xml'] = {content: Base64.encode64(theXML), transfer_encoding: :base64}
mail.attachments['some.pdf'] = thePDF

mail.content_type = mail.content_type.gsub('alternative', 'mixed')
mail.charset= 'UTF-8'
mail.content_transfer_encoding = 'quoted-printable'

Not intuitive at all, but reading the Pony source code kinda helped, as well as comparing a working .eml to whatever this gem was generating.

like image 122
Roberto Avatar answered Nov 15 '22 03:11

Roberto