Created
November 21, 2011 04:49
-
-
Save jinzhu/1381658 to your computer and use it in GitHub Desktop.
Ruby Mail for ISO-2022-JP / SHIFT_JIS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
gem 'mail', '=2.2.19' | |
require 'mail' | |
require 'nkf' | |
module Mail | |
module Encodings | |
class SevenBit | |
def self.decode(str) | |
NkfShell.to_jis(super, '-j') | |
end | |
end | |
class EightBit | |
def self.decode(str) | |
NkfShell.to_jis(str, '-s').to_lf | |
end | |
end | |
end | |
end | |
module Mail | |
class SubjectField | |
def wrapped_value # :nodoc: | |
if %w(ISO-2022-JP SHIFT-JIS).include? charset.upcase | |
"Subject: #{NkfShell.to_subject_jis(value, charset.upcase)}" | |
else | |
super | |
end | |
end | |
end | |
end | |
module Mail | |
class Ruby18 | |
def Ruby18.b_value_encode(str, encoding) | |
# Ruby 1.8 requires an encoding to work | |
raise ArgumentError, "Must supply an encoding" if encoding.nil? | |
encoding = encoding.to_s.upcase.gsub('_', '-') | |
if encoding.upcase == "ISO-2022-JP" | |
str = NkfShell.to_base64_jis(str, "-MBj") | |
elsif encoding.upcase == "SHIFT-JIS" | |
str = NkfShell.to_base64_jis(str, "-MBs") | |
else | |
str = Encodings::Base64.encode(str) | |
end | |
[str, encoding] | |
end | |
end | |
class Ruby19 | |
def Ruby19.b_value_encode(str, encoding) | |
encoding = str.encoding.to_s | |
if encoding.upcase == "ISO-2022-JP" | |
str = NKF.nkf('-MBj', str) | |
elsif encoding.upcase == "SHIFT-JIS" | |
str = NKF.nkf('-MBs', str) | |
else | |
str = Ruby19.encode_base64(str) | |
end | |
[str, encoding] | |
end | |
end | |
end | |
class NkfShell | |
def self.to_base64_jis(str,opt) | |
to_jis(str, opt) | |
end | |
def self.to_subject_jis(str, encoding) | |
if encoding == "ISO-2022-JP" | |
"=?ISO-2022-JP?B?#{Base64.encode64(to_jis(str,"-j")).delete("\r\n")}?=" | |
elsif encoding == "SHIFT-JIS" | |
"=?SHIFT-JIS?B?#{Base64.encode64(to_jis(str,"-s")).delete("\r\n")}?=" | |
end | |
end | |
def self.to_jis(str, argument="-j") | |
`bash -c "type /usr/local/bin/nkf" 2> /dev/null` | |
if $?.success? | |
IO.popen("/usr/local/bin/nkf #{argument}", "r+:utf-8:utf-8") do |nkf| | |
nkf.puts(str) | |
nkf.close_write() | |
nkf.read().to_s.chomp | |
end | |
else | |
puts "no `nkf` installed to /usr/local/bin/nkf" | |
NKF.nkf(argument, str) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment