Rails - ActionMailer - 如何发送自己创建的附件?

28
在 Rails3 的 ActionMailer 中,我想发送一个 .txt 文件附件。挑战在于这个 txt 文件并不存在,我需要根据我拥有的大块文本内容创建这个 txt 文件。
可能吗?有什么想法吗?谢谢。

嘿!我写了一篇深入讲解的博客文章 - Rails ActionMailer附件。基本上,在我们的邮件发送方法中,我们可以访问到一个attachments哈希。你可以将文件绑定到该哈希中,例如attachments['file.xlsx'] = File.read(/path/to/file.xlsx) - undefined
2个回答

72

在ActionMailer::Base的API文档中对文件进行了描述。

class ApplicationMailer < ActionMailer::Base
  def welcome(recipient)
    attachments['free_book.pdf'] = File.read('path/to/file.pdf')
    mail(:to => recipient, :subject => "New account information")
  end
end

但那并不一定要是一个文件,也可以是一个字符串。所以你可以做像这样的事情(我还使用了基于哈希的长格式,其中你也可以指定自己的MIME类型,你可以在ActionMailer::Base#attachments中找到有关此文档的说明):

class ApplicationMailer < ActionMailer::Base
  def welcome(recipient)
    attachments['filename.jpg'] = {:mime_type => 'application/mymimetype',
                                   :content => some_string }
    mail(:to => recipient, :subject => "New account information")
  end
end

谢谢,那个方法可行,但是附件显示在邮件顶部而不是底部,有什么想法吗? - AnApprentice
恐怕不是,我认为不应该发生这种情况。也许与您附件的Mimetype有关? - Marten Veldthuis
如果您想让附件显示在底部而不是顶部,请尝试这个答案:https://dev59.com/8FXTa4cB1Zd3GeqP3aGR#10787533 - Jackson Miller
29
有关一个API让我感到不安,因为它允许你创建附件但却没有将它们添加到邮件中...我希望至少在调用邮件方法时能够将附件传递进去... - Hakanai
4
完全同意。很奇怪,因为如果您创建一个Mail::Message对象,您可以向其中添加附件:ActionMailer::Base.mail(from: ..., to: ...).attachments['filename.jpg'] = some_string - Joshua Pinter
能否做类似的事情并附加 HTML 文件? - Christian

4

首先是发送电子邮件的方法

class ApplicationMailer < ActionMailer::Base
   def welcome(user, filename, path)
      attachments[filename] = File.read(path)
      mail(:to => user.email, :subject => "New account information")
   end
end

使用参数调用方法

UserMailer.welcome(user, filename, path).deliver

我认为这并没有回答真正的问题:“挑战在于这个txt文件不存在,而我想根据我拥有的大块文本创建txt文件”。 - MrBean Bremen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接