5
6

More than 5 years have passed since last update.

mikel/mailでメール受信した時のエンコード 文字化けを解決する

Last updated at Posted at 2015-01-28

mikel/mailを利用して、メール受信した時に"iso-2022-jp"とかだとエンコードしてあげないと化ける。
細かい部分は適当なのであしからず。


require 'mail'

Mail.defaults do
  retriever_method :pop3, :address    => "pop.example.com",
                          :port       => 995,
                          :user_name  => 'test@example.com',
                          :password   => 'password',
                          :enable_ssl => true
end

emails = Mail.find(:what => :last, :count => 3, :order => :desc)
emails.each do |mail|
  # 文字コード変換
  mail.header['Content-Type'].to_s =~ /charset=(\S+)/m
  if $1.present? && $1!='utf-8'
    charset = $1.downcase
    str = mail.body.decoded.to_s.encode("utf-8", charset, :invalid => :replace, :undef => :replace)
  else
    str = mail.body.decoded.to_s.force_encoding('utf-8')
  end
end

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6