Module: Sendmail

Defined in:
lib/egalite/sendmail.rb

Overview

many ways to designate mail addresses.

  1. array: you can put multiple addresses (string) into array.

1b array of array:

[["[email protected]","Hoge Taro"]]
  1. simple string: “[email protected]” works just fine.

  2. encoded string: Sendmail.address(“[email protected]”, “Hoge Taro”)

  3. hash: { “Hoge Taro” => “[email protected]” }

Defined Under Namespace

Classes: AttachmentsTooLarge, QualifiedMailbox

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.force_dkimObject

Returns the value of attribute force_dkim.



38
39
40
# File 'lib/egalite/sendmail.rb', line 38

def force_dkim
  @force_dkim
end

.lastmailObject (readonly)

Returns the value of attribute lastmail.



39
40
41
# File 'lib/egalite/sendmail.rb', line 39

def lastmail
  @lastmail
end

.mockObject

Returns the value of attribute mock.



38
39
40
# File 'lib/egalite/sendmail.rb', line 38

def mock
  @mock
end

.override_serverObject

Returns the value of attribute override_server.



38
39
40
# File 'lib/egalite/sendmail.rb', line 38

def override_server
  @override_server
end

Class Method Details

._send(text, envelope_from, to, host = 'localhost') ⇒ Object



218
219
220
221
222
223
224
225
226
# File 'lib/egalite/sendmail.rb', line 218

def _send(text, envelope_from, to, host = 'localhost')
  if @mock
    @lastmail = [text, envelope_from, to, host]
  else
    Net::SMTP.start(host) { |smtp|
      smtp.send_message(text, envelope_from, to)
    }
  end
end

.address(addrspec, name = nil, header = 'Reply-to') ⇒ Object



129
130
131
132
133
134
135
136
137
# File 'lib/egalite/sendmail.rb', line 129

def address(addrspec, name = nil, header='Reply-to') 
  # mailbox in RFC5322 section 3.4. not 'address' as in RFC.
  raise 'invalid mail address.' unless parse_addrspec(addrspec)
  if name and name.size > 0
    QualifiedMailbox.new(folding(header, "#{encode_phrase(header, name)} <#{addrspec}>"))
  else
    addrspec
  end
end

.atextObject



105
# File 'lib/egalite/sendmail.rb', line 105

def atext; '[0-9a-zA-Z!#$%&\'*+\-/=?\^_`{|}~]'; end

.atext_looseObject



106
# File 'lib/egalite/sendmail.rb', line 106

def atext_loose; '[0-9a-zA-Z!#$%&\'*+\-/=?\^_`{|}~.]'; end

.check_domain(s) ⇒ Object



108
109
110
# File 'lib/egalite/sendmail.rb', line 108

def check_domain(s)
  s =~ /\A#{atext}+?(\.#{atext}+?)+\Z/
end

.check_local_loose(s) ⇒ Object



111
112
113
# File 'lib/egalite/sendmail.rb', line 111

def check_local_loose(s)
  s =~ /\A#{atext_loose}+\Z/
end

.encode_phrase(header, s) ⇒ Object



91
92
93
94
95
96
97
# File 'lib/egalite/sendmail.rb', line 91

def encode_phrase(header, s)
  if multibyte?(s)
    multibyte_folding(header, s)
  else
    folding(header, quote_string(s))
  end
end

.encode_unstructured(header, s) ⇒ Object



98
99
100
101
102
103
104
# File 'lib/egalite/sendmail.rb', line 98

def encode_unstructured(header, s)
  if multibyte?(s)
    multibyte_folding(header, s)
  else
    folding(header, vchar(wsp(s)))
  end
end

.folding(h, s) ⇒ Object

folding white space. see RFC5322, section 2.3.3 and 3.2.2.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/egalite/sendmail.rb', line 40

def folding(h, s) # folding white space. see RFC5322, section 2.3.3 and 3.2.2.
  len = 78 - h.size - ": ".size
  len2nd = 78 - " ".size
  lines = []
  line = ""
  s.strip.split(/\s+/).each { |c| # each word (according to gmail's behavior)
    if (line+c).size > len
      len = len2nd
      lines << line.strip
      line = c + " "
    else
      line << c + " "
    end
  }
  lines << line.strip if line.size > 0
  lines.join("\n ")
end

.mailboxlist(value, header = 'Reply-to') ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/egalite/sendmail.rb', line 138

def mailboxlist(value, header = 'Reply-to')
  case value
    when QualifiedMailbox
      value
    when String
      parse_addrspec(value) ? value : nil
    when Hash
      folding(header, value.map { |name, address|
        address(address,name)
      }.join(', '))
    when Array
      folding(header, value.map { |v|
        v.is_a?(Array) ? address(v[0],v[1]) : mailboxlist(v,header)
      }.join(', '))
    else
      nil
  end
end

.message(body, params) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/egalite/sendmail.rb', line 156

def message(body, params)
  headers = {}
  
  raise "From must be exist." unless params[:from]
  raise "The number of sender must be zero or one." if params[:sender].is_a?(Array) and params[:sender].size > 1
  raise "When the number of 'from' is more than one, sender must be exist" if params[:from].is_a?(Array) and params[:from].size > 1 and not params[:sender]
  
  %w[From To Sender Reply-To Cc].each { |s|
    v = params[s.gsub(/-/,'_').downcase.to_sym]
    headers[s] = mailboxlist(v,s) if v and v.size >= 1
  }
  
  headers["Subject"] = encode_unstructured("Subject",params[:subject].to_s) if params[:subject]
  headers["MIME-Version"] = "1.0"
  date = params[:date] || Time.now
  headers["Date"] = date.is_a?(Time) ? date.rfc822 : date
  headers["Content-Type"] = params[:content_type]
  headers["Content-Type"] ||= "text/plain; charset=UTF-8"
  
  if params[:content_type] =~ /multipart/
    body = body
  elsif multibyte?(body)
    headers["Content-Transfer-Encoding"] = "base64"
    body = [body].pack('m')
  else
    headers["Content-Transfer-Encoding"] = "7bit"
  end

  params[:headers].each_pair { |k,v| headers[k] = v unless headers.key?(k)} if params.key?(:headers)

  text = [headers.map{|k,v| "#{k}: #{v}"}.join("\n"),body].join("\n\n")
end

.mime_combine(parts, type = "mixed") ⇒ Object

create MIME multipart



300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/egalite/sendmail.rb', line 300

def mime_combine(parts, type = "mixed")
  boundary = OpenSSL::Random.random_bytes(10).unpack('h*')[0]
  content_type = "multipart/#{type}; boundary=\"#{boundary}\""
  
  body = ""
  parts.each { |part|
    body << "--" + boundary
    body << "\n"
    body << part
  }
  body << "--" + boundary
  body << "--\n"
  [body, content_type]
end

.mime_header(header, s) ⇒ Object



314
315
316
317
318
319
320
# File 'lib/egalite/sendmail.rb', line 314

def mime_header(header,s)
  if multibyte?(s)
    header + '"' + multibyte_folding(header, s) + '"'
  else
    header + folding(header, quote_string(s))
  end
end

.mime_part(body, content_type = nil, filename = nil) ⇒ Object



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/egalite/sendmail.rb', line 321

def mime_part(body, content_type = nil, filename = nil)
  content_type = "text/plain; charset=UTF-8" unless content_type
  part = ""
  if filename
    part << "Content-Type: #{content_type};\n"
    part << mime_header(" name=", filename)
    part << "\n"
    part << "Content-Disposition: attachment;\n"
    part << mime_header(" filename=", filename)
    part << "\n"
    part << "Content-Transfer-Encoding: base64\n"
  else
    part << "Content-Type: #{content_type}\n"
    part << "Content-Transfer-Encoding: base64\n"
  end
  part << "\n"
  part << [body].pack('m')
end

.multibyte?(s) ⇒ Boolean

Returns:

  • (Boolean)


88
89
90
# File 'lib/egalite/sendmail.rb', line 88

def multibyte?(s)
  s.each_byte.any? { |c| c > 0x7f }
end

.multibyte_folding(h, s, encoding = 'UTF-8') ⇒ Object

RFC2047



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/egalite/sendmail.rb', line 57

def multibyte_folding(h, s, encoding = 'UTF-8') # RFC2047
  bracketsize = "=?#{encoding}?B??=".size
  len = 76 - h.size - ": ".size - bracketsize
  len2nd = 76 - bracketsize
  lines = []
  line = ""
  s = s.gsub(/\s+/, ' ').strip
  s.split(//).each { |c| # each character (including multi-byte ones)
    teststr = line+c
    teststr = NKF.nkf('-Wj',teststr) if encoding =~ /iso-2022-jp/i
    if [teststr].pack('m').chomp.size > len
      len = len2nd
      lines << line
      line = c
    else
      line << c
    end
  }
  lines << line if line.size > 0
  lines = lines.map { |s| "=?#{encoding}?B?#{[s].pack('m').gsub(/\n/,'')}?=" }
  lines.join("\n ")
end

.parse_addrspec(addrspec) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/egalite/sendmail.rb', line 114

def parse_addrspec(addrspec)
  # no support for CFWS, FWS, and domain-literal.
  if addrspec[0,1] == '"' # quoted-string
    addrspec =~ /\A(\".*?[^\\]\")\@(.+)\Z/
    (local, domain) = [$1, $2]
    return nil if local =~ /[\x00-\x1f\x7f]/
    return nil unless check_domain(domain)
    [local, domain]
  else
    (local, domain) = addrspec.split(/@/,2)
    return nil unless check_local_loose(local)
    return nil unless check_domain(domain)
    [local, domain]
  end
end

.quote_string(s) ⇒ Object



85
86
87
# File 'lib/egalite/sendmail.rb', line 85

def quote_string(s)
  '"' + vchar(wsp(s)).gsub(/\\/,"\\\\\\").gsub(/\"/,'\\\"') + '"'
end

.read_private_key(pem_filename) ⇒ Object



227
228
229
# File 'lib/egalite/sendmail.rb', line 227

def read_private_key(pem_filename)
  OpenSSL::PKey::RSA.new(open(pem_filename).read)
end

.send(body, params, host = 'localhost') ⇒ Object



245
246
247
# File 'lib/egalite/sendmail.rb', line 245

def send(body, params, host = 'localhost')
  send_inner_2(body, params, host, @force_dkim, {})
end

.send_inner_2(body, params, host, dkim, dkim_params) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/egalite/sendmail.rb', line 230

def send_inner_2(body, params, host, dkim, dkim_params)
  text = message(body, params)
  if dkim
    text = Dkim.sign(text,dkim_params)
  end
  envelope_from = _extract_addrspec(params[:envelope_from] || params[:sender] || params[:from])
  envelope_from = envelope_from[0] if envelope_from.is_a?(Array)
  host = @override_server if host == 'localhost' and @override_server
  _send(
    text,
    envelope_from,
    to_addresses(params),
    host
  )
end

.send_multipart(parts, params, host = 'localhost') ⇒ Object



251
252
253
254
255
# File 'lib/egalite/sendmail.rb', line 251

def send_multipart(parts, params, host = 'localhost')
  (body, content_type) = mime_combine(parts)
  params[:content_type] = content_type
  send_inner_2(body, params, host, @force_dkim, {})
end

.send_with_dkim(body, params, host = 'localhost', dkim_params = {}) ⇒ Object



248
249
250
# File 'lib/egalite/sendmail.rb', line 248

def send_with_dkim(body, params, host = 'localhost', dkim_params = {})
  send_inner_2(body, params, host, true, dkim_params)
end

.send_with_template(filename, params, host = 'localhost') ⇒ Object



271
272
273
274
275
276
277
278
279
# File 'lib/egalite/sendmail.rb', line 271

def send_with_template(filename, params, host = 'localhost')
  File.open("mail/"+ filename ,"r") { |f|
    text = f.read
    tengine = Egalite::HTMLTemplate.new
    tengine.default_escape = false
    text = tengine.handleTemplate(text,params)
    send(text, params, host)
  }
end

.send_with_uploaded_files(body, files, params, host = 'localhost') ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/egalite/sendmail.rb', line 256

def send_with_uploaded_files(body, files, params, host = 'localhost')
  # files should be Rack uploaded files.
  sum_size = 0
  files = [files].flatten
  parts = [mime_part(body)]
  parts += files.map { |f|
    File.open(f[:tempfile].path, "r") {|tf|
      binary = tf.read
      sum_size += binary.size
      raise AttachmentsTooLarge if sum_size >= 25 * 1000 * 1000
      mime_part(binary, f[:type], f[:filename])
    }
  }
  send_multipart(parts, params, host)
end

.to_addresses(params) ⇒ Object



212
213
214
215
216
217
# File 'lib/egalite/sendmail.rb', line 212

def to_addresses(params)
  addresses = [:to, :cc, :bcc].map { |s|
    _extract_addrspec(params[s])
  }
  addresses.flatten.compact.uniq
end

.vchar(s) ⇒ Object



79
80
81
# File 'lib/egalite/sendmail.rb', line 79

def vchar(s)
  s.gsub(/[\x00-\x1f\x7f]/,'')
end

.verify_address(email) ⇒ Object

check validity of email address with DNS lookup.



284
285
286
287
288
289
290
291
292
293
294
# File 'lib/egalite/sendmail.rb', line 284

def verify_address(email)
  (local,domain) = parse_addrspec(email)
  return false unless domain
  mx = Resolv::DNS.new.getresource(domain, Resolv::DNS::Resource::IN::MX) rescue nil
  return true if mx
  a = Resolv::DNS.new.getresource(domain, Resolv::DNS::Resource::IN::A) rescue nil
  return true if a
  aaaa = Resolv::DNS.new.getresource(domain, Resolv::DNS::Resource::IN::AAAA) rescue nil
  return true if aaaa
  false
end

.wsp(s) ⇒ Object



82
83
84
# File 'lib/egalite/sendmail.rb', line 82

def wsp(s)
  s.gsub(/\s+/,' ')
end