swissmade
swissmade

Reputation: 87

Ruby send email with an attachment with /usr/sbin/sendmail

I am trying to send an email with a csv file for attachement. I do the following but I only receive an email with a empty csv file (and not with the content of it). Can you please help me on that? I don't want to use any extra library so please don't tell me to use pony or so ;-)

to="[email protected]"
subject='The subject'
from='"Name" <[email protected]>'
description ="Desc"

csvnamefile = "/path/to/file/filename.csv"

puts  value = %x[/usr/sbin/sendmail #{to} << EOF
subject: #{subject}
from: #{from}
Content-Description: "#{csvnamefile}"
Content-Type: multipart/mixed; name="#{csvnamefile}"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{csvnamefile}"
Description : #{description}
EOF]

Thanks

Upvotes: 0

Views: 1573

Answers (2)

swissmade
swissmade

Reputation: 87

Thanks Alex. I could make it work with your informations. The final working result looks like this:

binary = File.read(csvnamefile)
encoded = [binary].pack("m")    # base64 econding
puts  value = %x[/usr/sbin/sendmail #{to} << EOF
subject: #{subject}
from: #{from}
Content-Description: "#{csvnamefile}"
Content-Type: text/csv; name="#{csvnamefile}"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{csvnamefile}"
#{encoded}
EOF]

Upvotes: 1

AlexD
AlexD

Reputation: 910

/usr/sbin/sendmail doesn't know anything about attachments and treats email message body according to RFC 5322 as flat US-ASCII text. To send a file as attachment you need to format your message as MIME message according to RFC 2045. For example of such a message see Appendix A to RFC 2049.

Upvotes: 0

Related Questions