mailfactory是rubyforge上一個簡單的郵件發送包, 通過它我們可以很方便的發送帶附件和html格式的郵件,不過目前的mailfactory在支援中文上有一些問題, 需要打一個補丁
先需要通過 gem install mailfactory 安裝
然後是對mailfactory的補丁,可以直接修改mailfactory的源檔案,也可以單獨作一個檔案mailfactory_enhence.rb,只要在require 'mailfactory'以後require 它就可以了
# 對mailfactory打補丁,增加了一個encoding參數
class MailFactory
attr_accessor :encoding
def html=(newhtml)
@html = "<html>\n<head>\n<meta content=\"text/html;charset=#{encoding}\" http-equiv=\"Content-Type\">\n</head>\n<body bgcolor=\"#ffffff\" text=\"#000000\">\n#{newhtml}\n</body>\n</html>"
end
def body_to_s()
body = Array.new()
# simple message with one part
if(!multipart?())
return(@text)
else
body << "This is a multi-part message in MIME format.\r\n\r\n--#{@attachmentboundary}\r\nContent-Type: multipart/alternative; boundary=\"#{@bodyboundary}\""
if(@attachments.length > 0)
# text part
body << "#{buildbodyboundary("text/plain; charset=#{encoding}; format=flowed", '7bit')}\r\n\r\n#{@text}"
# html part
body << "#{buildbodyboundary("text/html; charset=#{encoding}", '7bit')}\r\n\r\n#{@html}"
body << "--#{@bodyboundary}--"
# and, the attachments
if(@attachments.length > 0)
@attachments.each() { |attachment|
body << "#{buildattachmentboundary(attachment)}\r\n\r\n#{attachment['attachment']}"
}
body << "\r\n--#{@attachmentboundary}--"
end
else
# text part
body << "#{buildbodyboundary("text/plain; charset=#{encoding}; format=flowed", '7bit')}\r\n\r\n#{@text}"
# html part
body << "#{buildbodyboundary("text/html; charset=#{encoding}", '7bit')}\r\n\r\n#{@html}"
body << "--#{@bodyboundary}--"
end
return(body.join("\r\n\r\n"))
end
end
end
最後開始使用: mailfactory的使用非常簡單, 例子如下
#使用方法非常簡單
mail=MailFactory.new
mail.encoding="GBK" #設定encoding
mail.to=['a@sina.com','b@sina.com'].join(',') #多個收件者
mail.from='from@host.com'
mail.subject='subject'
mail.html='</font color="red">htmlconternt</font>'
mail.text='please use html view'
mail.attach('/usr/local/test.file')
Net::SMTP.start(@smtp_host) do |smtp|
smtp.send_message(msgstr,from,to)
end