Mailfactory is a simple mail package on rubyforge. With this package, we can easily send emails with attachments and HTML formats. However, currently, mailfactory has some problems in Chinese support, A patch is required.
Install mailfactory using gem install
Then we patch mailfactory. You can directly modify the source file of mailfactory, or you can create a separate file mailfactory_enhence.rb. You only need to require 'mailfactory 'and then require it.
# Patches mailfactory and adds an encoding parameter.
Class mailfactory
Attr_accessor : Encoding
Def html = (Newhtml)
@ Html = " <HTML> \ n " Text / HTML; charset = # {Encoding} \ "http-equiv = \" Content-Type \ "> \ n
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 -- # {@ 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 # {@ text }"
# HTML part
Body < " # {Buildbodyboundary ( " Text / HTML; charset = # {Encoding} ", '7bit ')} \ r \ n # {@ HTML }"
Body < " -- # {@ Bodyboundary }-- "
# And, the attachments
If ( @ Attachments . Length > 0 )
@ Attachments . Each (){ | Attachment |
Body < " # {Buildattachmentboundary (Attachment)} \ r \ n # {attachment ['attachment']} "
}
Body < " \ R \ n -- # {@ attachmentboundary }-- "
End
Else
# Text part
Body < " # {Buildbodyboundary ( " Text / Plain; charset = # {Encoding}; format = flowed ", '7bit ')} \ r \ n # {@ text }"
# HTML part
Body < " # {Buildbodyboundary ( " Text / HTML; charset = # {Encoding} ", '7bit ')} \ r \ n # {@ HTML }"
Body < " -- # {@ Bodyboundary }-- "
End
Return (Body . Join ( " \ R \ n " ))
End
End
End
Finally, use mailfactory. The example is as follows:
# Easy to use
Mail = Mailfactory . New
Mail . Encoding = " GBK " # Set Encoding
Mail . To = [ ' A@sina.com ' , ' B @sina.com ' ] . Join ( ' , ' ) # Multiple recipients
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