2016-05-04 3 views
0

ルビーを使用して電子メールの添付ファイルとして特定のフォルダ内のすべてのファイルを送信しようとしています。 フォルダ内のすべてのファイルを読み取り、それらをルビーの電子メール添付ファイルとして送信するにはどうすればよいですか? 現在、以下のコードを使用して、添付ファイルとして1つのファイルを送信できます。フォルダ内のすべてのファイルをルビーの電子メール添付ファイルとして送信する方法

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 <[email protected]> 
    To: A Test User <[email protected]> 
    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, '[email protected]', 
         ['[email protected]']) 
    end 
    rescue Exception => e 
    print "Exception occured: " + e 
    end 
+1

をあなたがゼロからメールサービスを実装しようとしている理由はありますか?既存の宝石を使うだけではあまり簡単ではないでしょうか? https://github.com/mikel/mail? –

+0

私はまったく新しいルビーです。その場合も、添付ファイルとしてフォルダ内のすべてのファイルを送信する方法。 –

答えて

0

ここでの重要な部分は、ディレクトリ内のすべてのファイルをループにし、添付ファイルとしてそれらのそれぞれを追加します。

これを行うために元のコードを変更することはできますが、はるかに簡単な解決法があります。例えば

は、そのようmailhttps://github.com/mikel/mail)とルビーの宝石を使用して、あなたのコードに多大な簡略化することができます。

Mail.deliver do 
    from  '[email protected]' 
    to  '[email protected]' 
    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 
関連する問題