text 18 Jan Send mail with attachment via ruby SMTP

Vediamo come inviare una mail con allegato usando l’API di Ruby per SMTP. Di seguito il codice:

def send_newsletter

  body = "Testo del messaggio"

  filecontent = File.read("allegato.pdf")
  encodedcontent = [filecontent].pack("m") # base64
  marker = "AUNIQUEMARKER"

  # Define the main headers.
  part1 =<<EOF
From: from@mail.com <Pioz>
To: <to@mail.it>
Subject: Oggetto del messaggio
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF

  # Define the message action
  part2 =<<EOF
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding:8bit

#{body}
--#{marker}
EOF

  # Define the attachment section
  part3 =<<EOF
Content-Type: application/pdf; name="allegato.pdf"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="allegato.pdf"

#{encodedcontent}
--#{marker}--
EOF

  mailtext = part1 + part2 + part3

  Net::SMTP.start('mail.server.it', 25, 'mail.server.it', USERNAME, PASSWORD, :login) do |smtp|
    smtp.send_message mailtext, "from@mail.com", "to@mail.it"
  end
end

Ecco.. in pratica inviamo una mail in multipart divisa in tre parti: una per dire che e` multipart, una per il body della mail (formato HTML nell’esempio) e l’ultima per l’allegato.


blog comments powered by Disqus