ActionMailer
已经依赖于Mail
gem,您可以使用它来解析传入的电子邮件并提取您想要的部分。处理多部分电子邮件特别有用。
require 'mail'
class IncomingEmails < ApplicationController
skip_before_filter :verify_authenticity_token
def receive_email
comment = Comment.new(find_user, message_body)
comment.save
rescue
# Reject the message
logger.error { "Incoming email with invalid data." }
end
private
def email_message
@email_message ||= Mail.new(params[:message])
# Alternatively, if you don't have all the info wrapped in a
# params[:message] parameter:
#
# Mail.new do
# to params[:to]
# from params[:from]
# subject params[:subject]
# body params[:body]
# end
end
def find_user
# Find the user by the randomly generated secret email address, using
# the email found in the TO header of the email.
User.find_by_secret_email(email_message.to.first) or raise "Unknown User"
end
def message_body
# The message body could contain more than one part, for example when
# the user sends an html and a text version of the message. In that case
# the text version will come in the `#text_part` of the mail object.
text_part = email_message.multipart? ? email_message.text_part : email_message.body
text_part.decoded
end
end