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:
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
Now don't start spamming!

5 Responses to “How to send multipart/alternative e-mail with inline attachments”

  1. Coda Hale Says:
    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.)
  2. Coda Hale Says:
    Oh hey, wait. I wrote too soon. Nevermind. Implicit multipart is a totally different thing. That's a damn cool trick! Thanks!
  3. Justin Halsall Says:

    Thanks for saving me all the trouble of trying to get it figured out myself!

  4. c.the_greek Says:

    Great trick, how do you write a spec for it? multipart are a bit tricky too

  5. Mark Says:

    How do you add the image in the view?

Leave a Reply

I am a human (check this)

Remember: escape your underscores \_ and indent code at least 4 spaces or incur the wrath of smartypants.