Sending Emails with Rails, multipart html plain with Attachments
When trying to send attachments along with type versons of an email (html and plain text) you might notice that there is no content in your email message. While I found this out too. Simple if not over the top solution.
The trick is that you have to put the html and plain part inside a “multipart/alternative” block. If you don’t you’ll end up sending no message with the email, or you’ll send two attachments, the actual attachment (image etc.) and a message attachment. Not ideal!
Koz, so a friend of mine pointed out my problems and I ended up with the following.
def send_photo(employee)
recipients “[email protected]”
from “[email protected]”
subject “Security Photo”
sent_on Time.now
part(:content_type => “multipart/alternative”) do |p|
p.part :content_type => “text/html”, :body => render_message(“send_photo.text.html.erb”, :employee => employee)
p.part :content_type => “text/plain”, :body => render_message(“send_photo.text.plain.erb”, :employee => employee)
end
unless employee.security_photo.path.nil?
attachment :content_type => employee.security_photo_content_type,
:body => File.read(employee.security_photo.path(:medium_email))
end
end
recipients “[email protected]”
from “[email protected]”
subject “Security Photo”
sent_on Time.now
part(:content_type => “multipart/alternative”) do |p|
p.part :content_type => “text/html”, :body => render_message(“send_photo.text.html.erb”, :employee => employee)
p.part :content_type => “text/plain”, :body => render_message(“send_photo.text.plain.erb”, :employee => employee)
end
unless employee.security_photo.path.nil?
attachment :content_type => employee.security_photo_content_type,
:body => File.read(employee.security_photo.path(:medium_email))
end
end
Related Posts
Posted on June 3, 2010 at 5:36 am by Jordan Carter · Permalink
In: Ruby on Rails · Tagged with: attachments, email, multipart
In: Ruby on Rails · Tagged with: attachments, email, multipart
on July 1, 2010 at 2:56 am
Permalink
Thanks – after spending half an hour trying to figure out why a multipart message with an attachment had no text, I found your post and fixed it in two minutes
on November 8, 2011 at 8:16 am
Permalink
I just ran into this with my ics attachment. Thanks.
on August 11, 2012 at 5:19 am
Permalink
You save my day sir. Thank you very much!