在铁路邮件中附件不合适

我发送带附件的邮件(1.pdf),但在邮件中它并没有显示1.pdf而是显示一些名为“ATT008220.dat”的随机文件。

我正在使用Rails 3.0以下是我正在使用的代码:

@file = File.read('c:/1.pdf') @file.force_encoding('BINARY') attachment "application/octet-stream" do |a| a.body = @file end 

谁知道它为什么会发生? 任何的想法?

感谢和问候,

苛刻的拉瓦尔。

编辑:: —-邮件发送方式:

 def contact(recipient, subject, message, sent_at = Time.now) @subject = subject @recipients = recipient @from = 'harsh@apprika.com' @sent_on = sent_at @body = message #@file = File.read('c:/1.pdf') #@file.force_encoding('US_ASCII') #attachment "multipart/alternative" do |a| # a.body = @file #end attachments['1.pdf'] = {:mime_type => 'application/pdf',:content => File.read('c:/1.pdf')} @headers = {} end 

尝试使用.xlsx文件作为附件发送邮件时,我遇到了类似的问题。 要使它工作,我必须做:

 attachments['filename.xlsx'] = { :encoding => 'base64', :content => Base64.encode64(File.read(filename)) } 

这部分在Mailer指南的2.3.2部分中提到: http : //guides.rubyonrails.org/action_mailer_basics.html#complete-list-of-action-mailer-methods

我想,你需要指定文件名

 @file = File.read('c:/1.pdf') @file.force_encoding('BINARY') attachment "application/octet-stream" do |a| a.body = @file a.filename = "1.pdf" end 

我会使用"application/pdf"作为pdf文件。

编辑:

我查看了Rails 3指南,我没有看到任何上述语法的示例。 相反,他们使用这样的东西:

 attachments['1.pdf'] = File.read('c:/1.pdf') 

或者有其他选择:

 attachments['1.pdf'] = {:mime_type => 'application/octet-stream', :content => File.read('c:/1.pdf') } 

看看这里有更多的信息。

编辑2:

我想从评论中回答你的问题。 我没有在Rails 3中使用过邮件,但我在Rails 2.3.X中使用它,这里有一些适用于我的代码:

 attachment :content_type => "application/msword", :body => File.read("files/word.doc"), :filename => "word.doc" attachment "application/pdf" do |a| a.body = File.read("files/some_pdf.pdf") a.filename = "umowa.pdf" end 

在Rails 3中,邮件程序API发生了变化。 你应该使用新的API。 顺便说一句。 如果我的第一个例子有效,你也可以尝试 – 它使用哈希而不是块。

另一个编辑:

我认为你应该使用mail对象来发送邮件。 以下是Rails指南的示例:

 def welcome_email(user) @user = user @url = user_url(@user) mail(:to => user.email, :subject => "Welcome to My Awesome Site") end 

message应该在邮件程序视图中呈现。 我认为你有问题,因为你正在将旧的邮件程序API与新邮件混合使用。 看一看这里如何以“新方式”逐步完成。

从Rails 3(x)开始,您的内容处置决定了最终用户接收文件名的方式。

代替:

 attachments['1.pdf'] = {:mime_type => 'application/pdf',:content => File.read('c:/1.pdf')} 

用这个:

 # I like to rewrite the file name to exclude any whitespaces safe_name = file_name.gsub(/[^0-9a-z\.]/i,"-") attachments[safe_name] = { :content => File.read(file_name), :content_disposition => "attachment; filename=\"#{safe_name}\"" } 

您可以包含mime_type,但除非您解释附加内容的顺序,否则您可能会得到一些令人讨厌的结果,除非您在邮件程序中指定了类似的内容:

 class SampleNotifications < ActionMailer::Base # my_mailer :content_type => 'multipart/alternative', :parts_order => [ "text/plain", "text/enriched", "text/html", "application/octet-stream" ] def notify ... something like the code above end end 

做如下:

添加以下内容给actionmailer: –

 def send_mail attachments['1.pdf'] = File.read('c:/1.pdf') mail(:to => "harsh@xyz.com", :subject => "xyz", :from=>"harsh@xyz.com") mail.deliver end 

注意: – 确保smtp设置正确,并且相应的操作对应的文件(在此示例中为send_mail.rhtml)位于相应的文件夹下。

希望这可以帮助。