我正在尝试使用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
答案 0 :(得分:0)
这里的重要部分是遍历目录中的所有文件,并将每个文件作为附件添加。
我可以修改您的原始代码来执行此操作,但有更简单的解决方案。
例如,使用诸如mail
(https://github.com/mikel/mail)之类的ruby gem,您可以大大简化代码:
Mail.deliver do
from 'me@fromdomain.net'
to 'mytest@todmain.com'
subject 'Sending Attachement'
body 'This is a test email to send an attachement.'
Dir.glob('/tmp/files_to_attach/*.txt') do |file|
add_file file
end
end