最近Rails项目的最后两个功能就是进行邮件通知和上传附件管理,这里使用了Rails框架下的ActionMailer和paperclip两个来完成的
一、ActionMailer使用
首先要忽略邮件的错误,进入config/environments,打开development.rb文件,将config.action_mailer.raise_delivery_errors设定为false
config.action_mailer.raise_delivery_errors = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { host: "http://localhost:3000" }
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => "587",
:domain => "gmail.com",
:authentication => "plain",
:user_name => "[email protected]",
:password => "123456",
:enable_starttls_auto => true
}
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { host: "http://localhost:3000" }
config.action_mailer.smtp_settings = {
:address => "smtp.163.com",
:port => "25",
:authentication => "login",
:user_name => "[email protected]",
:password => "xxxxx",
:enable_starttls_auto => true
}
然后可以生成一封Email模板,比如下面:
rails generate mailer UserMailer notify_comment
class UserMailer < ActionMailer::Base
default :from => "[email protected]"
def notify_comment(user, comment)
@comment = comment
mail(:to => user .email, :subject => "New Comment")
end
end
此外,邮件的模板在app/views/user_mailer/notify_comment.text.erb和notify_comment.html.erb,一个是纯文本模式,一个是html模式。
如果要发送邮件,可以在自己的代码种加上如下代码:
UserMailer.notify_comment(user, comment).deliver_now!
这样就可以将邮件发送成功了。
二、paperclip使用
paperclip是一个图片附件的管理组件,非常方便,在使用这个之前必须确保已经安装了ImageMagick这个工具,如果没有可以安装
Mac下就用brew
brew install imagemagick
sudo apt-get install imagemagick
注意安装完成后要确定imagemagick这次程序默认在/usr/local/bin/路径下,否则要修改config/environments/development.rb
Paperclip.options[:command_path] = "/usr/local/bin/"
gem "paperclip", "~> 4.2"
然后bundle install
一般上传附件都是提交在一个表单的时候,因此一般表单都对应这一个model,这样需要对这个model添加一个属性来记录这个附件,比如model为User
首先添加migration
rails g migration add_avatar_columns_to_users
class AddAvatarColumnsToUsers < ActiveRecord::Migration
def up
add_attachment :users, :avatar
end
def down
remove_attachment :users, :avatar
end
end
然后执行数据库迁移命令
rake db:migrate
<%= form_for @user, :url => users_path, :html => { :multipart => true } do |form| %>
<%= form.file_field :avatar %>
<% end %>
def create
@user = User.create( user_params )
end
private
# Use strong_parameters for attribute whitelisting
# Be sure to update your create() and update() controller methods.
def user_params
params.require(:user).permit(:avatar)
end
class User < ActiveRecord::Base
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end
<%= image_tag @user.avatar.url %>
<%= image_tag @user.avatar.url(:medium) %>
<%= image_tag @user.avatar.url(:thumb) %>