1
|
|
|
require 'mime' |
2
|
|
|
require 'mime/types' |
3
|
|
|
|
4
|
|
|
module MIMEBuilder |
5
|
|
|
class Filepath |
6
|
|
|
attr_accessor :mime |
7
|
|
|
attr_accessor :filepath |
8
|
|
|
|
9
|
|
|
# {:base64_encode bool, :content_type string, :content_id_disable bool} |
10
|
|
|
def initialize(filepath, opts={}) |
11
|
|
|
|
12
|
|
|
if opts.has_key?(:base64_encode) && opts[:base64_encode] |
13
|
|
|
@base64_encode = true |
14
|
|
|
else |
15
|
|
|
@base64_encode = false |
16
|
|
|
end |
17
|
|
|
|
18
|
|
|
@mime = create_mime(filepath) |
19
|
|
|
|
20
|
|
|
if opts.has_key?(:content_id_disable) |
21
|
|
|
@mime.headers.delete('Content-Id') |
22
|
|
|
end |
23
|
|
|
|
24
|
|
|
@mime.headers.set( |
25
|
|
|
'Content-Type', |
26
|
|
|
get_file_content_type(filepath, opts[:content_type]) |
27
|
|
|
) |
28
|
|
|
|
29
|
|
|
if opts.has_key?(:is_attachment) && opts[:is_attachment] |
30
|
|
|
@mime.headers.set( |
31
|
|
|
'Content-Disposition', |
32
|
|
|
get_attachment_content_disposition(filepath) |
33
|
|
|
) |
34
|
|
|
end |
35
|
|
|
end |
36
|
|
|
|
37
|
|
|
def create_mime(filepath) |
38
|
|
|
bytes = read_file_bytes(filepath) |
39
|
|
|
|
40
|
|
|
if @base64_encode |
41
|
|
|
mime = MIME::Text.new(Base64.encode64(bytes)) |
42
|
|
|
mime.headers.set('Content-Transfer-Encoding', 'base64') |
43
|
|
|
return mime |
44
|
|
|
end |
45
|
|
|
|
46
|
|
|
return MIME::Application.new(bytes) |
47
|
|
|
end |
48
|
|
|
|
49
|
|
|
def read_file_bytes(filepath=nil) |
50
|
|
|
unless File.file?(filepath.to_s) |
51
|
|
|
raise "File \"#{filepath.to_s}\" does not exist or cannot be read" |
52
|
|
|
end |
53
|
|
|
|
54
|
|
|
# Ruby 1.8.7 support |
55
|
|
|
file_bytes = RUBY_VERSION < '1.9' \ |
56
|
|
|
? File.open(filepath, 'rb') { |f| f.read } \ |
57
|
|
|
: File.open(filepath, 'rb:BINARY') { |f| f.read } |
58
|
|
|
|
59
|
|
|
return file_bytes |
60
|
|
|
end |
61
|
|
|
|
62
|
|
|
def get_file_content_type(filepath=nil, content_type=nil) |
63
|
|
|
if (content_type.is_a?(String) && content_type =~ /^[^\/\s]+\/[^\/\s]+/) |
64
|
|
|
return content_type |
65
|
|
|
end |
66
|
|
|
return MIME::Types.type_for(filepath).first.content_type \ |
67
|
|
|
|| 'application/octet-stream' |
68
|
|
|
end |
69
|
|
|
|
70
|
|
|
def get_attachment_content_disposition(filepath=nil) |
71
|
|
|
filename = File.basename(filepath.to_s) |
72
|
|
|
if filename.is_a?(String) && filename.length > 0 |
73
|
|
|
return "attachment; filename=\"#{filename}\"" |
74
|
|
|
else |
75
|
|
|
return 'attachment' |
76
|
|
|
end |
77
|
|
|
end |
78
|
|
|
|
79
|
|
|
end |
80
|
|
|
end |
81
|
|
|
|