How to send multipart/alternative e-mail with inline attachments
Liquid error: undefined method `login' for nil:NilClass : February 19th, 2006
The benefit of multipart/alternative messages is that the MUA will pick the part that it knows how to render. Usually, the two alternative representations are `text/plain` and `text/html`, and those are the two we're going to use in this example.
Although there's lots of examples on how to do this, none tell you how to add images to your html mail. And we _do_ want images that we can see in the e-mail, not attachments.
### The code
I won't bore you with all the problems I had (like only the image showing, the image isn't visible as it only appears as an attachment, etc.), so here's the code:
Now don't start spamming!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Notifier < ActionMailer::Base def order_confirmation(order) subject 'Order confirmation' recipients order.customer.email_address_with_name from 'Exemplary Products <info@example.com>' content_type 'multipart/alternative' part :content_type => 'text/plain', :body => render_message('registration_notifier_plain', :order => order) part 'multipart/related' do |p| # This next line makes it all work p.content_type='text/html' p.part :content_type => 'text/html', :body => render_message('registration_notifier_html', :order => order) p.part :content_type => 'image/gif', :content_disposition => 'inline', :transfer_encoding => 'base64', :body => File.read("#{RAILS_ROOT}/public/images/logo.gif") end end end |
5 Responses to “How to send multipart/alternative e-mail with inline attachments”
Leave a Reply
Remember: escape your underscores \_ and indent code at least 4 spaces or incur the wrath of smartypants.
February 19th, 2006 at 10:47 AM Or you could just have two views: action_name.text.plain.rhtml action_name.text.html.rhtml And Rails does the rest for you. (Well, you still need to add the GIF file, but yeah.)
February 19th, 2006 at 10:53 AM Oh hey, wait. I wrote too soon. Nevermind. Implicit multipart is a totally different thing. That's a damn cool trick! Thanks!
March 7th, 2007 at 03:38 PM
Thanks for saving me all the trouble of trying to get it figured out myself!
January 22nd, 2008 at 08:20 AM
Great trick, how do you write a spec for it? multipart are a bit tricky too
December 1st, 2008 at 09:40 PM
How do you add the image in the view?