电子邮件不是使用Zip中的Zipped附件(csv文件)发送的

时间:2014-08-13 14:29:53

标签: ruby-on-rails ruby csv smtp zip

我使用以下代码发送带有zip附件的邮件(CSV文件),

     def send_mail()
    from = "admin@domainname.com"
    to = "user@domainname.com"
    cc = cc

    filename = "D:/test.zip"
    # Read a file and encode it into base64 format
    filecontent = File.read(filename).strip
    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:  #{from}
To:  #{to}
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: application/zip; name=\"#{"test.zip"}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{"test.zip"}"

#{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, from, to)

      end
    rescue Exception => e
      puts "Exception occured: " + e
    end  
  end

但是这些电子邮件都是恶作剧。

我使用的是Ruby-18.7和Rails 2.3.2

如果代码中有任何问题,请告诉我吗?

谢谢

Periyasamy

1 个答案:

答案 0 :(得分:0)

抱歉,我真的无法理解你在做什么,因此我可能不会回答这个问题。但是,如果您完全错误,请尝试以下方法:

The Mailer

class UserMailer < ActionMailer::Base
  default from: 'email@example.com'

  def send_email(user)
    @user = user
    @url  = 'http://example.com/login'
    mail(to: @user.email, subject: 'Welcome to My Awesome Site')
  end
end

现在是邮件程序的视图(.html.erb)文件

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Welcome to example.com, <%= @user.name %></h1>
    <p>
      You have successfully signed up to example.com,
      your username is: <%= @user.name %>.<br>
    </p>
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>

这将生成一个普通邮件。

最后添加附件:

      def send_email(user)
        @user = user
        @url  = 'http://example.com/login'
        attachments['my_compressed_file.zip'] = File.read('path/to/file.zip')
        mail(to: @user.email, subject: 'Welcome to My Awesome Site')
      end

如果您仍然无法发送附件,我建议您验证附加的文件权限。

注意:

如果默认的ActionMailer失败,您可以尝试其他宝石,例如pony