【问题标题】:how to send all files in a folder as email attachments in ruby如何在ruby中将文件夹中的所有文件作为电子邮件附件发送
【发布时间】: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​​ 完全陌生。在这种情况下,如何将文件夹中的所有文件作为附件发送。

标签: ruby email-attachments


【解决方案1】:

这里的重要部分是遍历目录中的所有文件,并将每个文件添加为附件。

我可以修改您的原始代码来执行此操作,但有更简单的解决方案。

例如,使用 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

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 2020-03-15
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2015-12-21
    相关资源
    最近更新 更多