Ruby-on-rails Rails - ActionMailer - 如何发送您创建的附件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5145870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails - ActionMailer - How to send an attachment that you create?
提问by AnApprentice
In rails3 w ActionMailer, I want to send a .txt file attachment. The challenge is this txt file does not exist but rather I want to create the txt file given a large block of text that I have.
在 rails3 w ActionMailer 中,我想发送一个 .txt 文件附件。挑战是这个 txt 文件不存在,而是我想在给定一大块文本的情况下创建 txt 文件。
Possible? Ideas? Thanks
可能的?想法?谢谢
回答by Marten Veldthuis
It's described for files in the API documentationof ActionMailer::Base
它在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
But that doesn't have to be a File, it can be a string too. So you could do something like (I'm also using the longer Hash-based form where you can specify your own mimetype too, you can find documentation for this in ActionMailer::Base#attachments):
但这不一定是一个文件,它也可以是一个字符串。所以你可以做一些类似的事情(我也使用更长的基于哈希的形式,你也可以在其中指定你自己的 mimetype,你可以在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
回答by Rafael Carvalho
First the method to send email
首先是发送电子邮件的方法
class ApplicationMailer < ActionMailer::Base
def welcome(user, filename, path)
attachments[filename] = File.read(path)
mail(:to => user.email, :subject => "New account information")
end
end
Call the method with the params
使用参数调用方法
UserMailer.welcome(user, filename, path).deliver

