【发布时间】:2016-05-04 09:38:10
【问题描述】:
我正在尝试使用 ruby 将特定文件夹中的所有文件作为电子邮件附件发送。 如何读取文件夹中的所有文件并将它们作为电子邮件附件发送到 ruby 中? 截至目前,我可以使用以下代码将一个文件作为电子邮件附件发送。
require 'net/smtp'
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
filecontent = File.read(filename)
encodedcontent = [filecontent].pack("m") # base64
marker = "AUNIQUEMARKER"
body =<<EOF
This is a test email to send an attachement.
EOF
# Define the main headers.
part1 =<<EOF
From: Private Person <me@fromdomain.net>
To: A Test User <test@todmain.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF
# Define the message action
part2 =<<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit
#{body}
--#{marker}
EOF
# Define the attachment section
part3 =<<EOF
Content-Type: multipart/mixed; name=\"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"
#{encodedcontent}
--#{marker}--
EOF
mailtext = part1 + part2 + part3
# Let's put our code in safe area
begin
Net::SMTP.start('localhost') do |smtp|
smtp.sendmail(mailtext, 'me@fromdomain.net',
['test@todmain.com'])
end
rescue Exception => e
print "Exception occured: " + e
end
【问题讨论】:
-
您从头开始实施邮件服务有什么原因吗?仅使用现有的 gem 会不会容易得多,例如github.com/mikel/mail ?
-
我对 ruby 完全陌生。在这种情况下,如何将文件夹中的所有文件作为附件发送。