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