Question

I have a question about net/smtp

For html emails you have to set this in the header of the email content-type: text/html . However, if you want to send an attachment you have to change it to content-type: multipart/mixed. Which would make the html email...not html anymore.

So the question is.. how do I accomplish both? HTML and attachment?

Thank you

Was it helpful?

Solution

Each attachment has its own MIME type

Each part of a multipart email has its own MIME type. So, while the email's content-type is "multipart/mixed", each attachment has its own MIME type (text, HTML, etc).

Here is an example multipart email from MIME and HTML in Email by Doug Steinwand:

To: whoever@someplace.com
Subject: MIME test
Content-type: multipart/mixed; boundary="theBoundaryString"

--theBoundaryString

Plain text message goes in this part. Notice that it
has a blank line before it starts, meaning that this
part has no additional headers.

--theBoundaryString
Content-Type: text/html
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
Content-Base: "http://somewebsite.com/"

<body><font size=4>This</font> is a 
<i>test</i>.
--theBoundaryString--

Here you can see that the text attachment has no explicit content type. When an attachment has no explicit content type, it is US ASCII TEXT. The HTML attachment has a content type of "text/html". There could be other attachments, each with their own MIME type.

Consider using the "mail" Gem

The mail gem makes sending and parsing multi-part emails very easy. It is stable, well maintained, and widely used.

This example from its README shows how to send a multi-part mail with a text part and an HTML part:

mail = Mail.deliver do
  to      'nicolas@test.lindsaar.net.au'
  from    'Mikel Lindsaar <mikel@test.lindsaar.net.au>'
  subject 'First multipart email sent with Mail'

  text_part do
    body 'This is plain text'
  end

  html_part do
    content_type 'text/html; charset=UTF-8'
    body '<h1>This is HTML</h1>'
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top