Rails Railscasts-china 20 期,如何在 Rails 中发送邮件

poshboytl · 2012年10月02日 · 最后由 paul1113 回复于 2014年08月19日 · 7827 次阅读

http://railscasts-china.com/episodes/how-to-send-emails-in-rails

介绍如何在 Rails 中发送 Email.

在 console 中创建 mailer

rails g mailer CommentMailer

Mailer 代码,

class CommentMailer < ActionMailer::Base
  default from: "[email protected]"

  def comment_notify_email(comment)
    @comment = comment
    @url = post_url(@comment.post, host: 'localhost')

    mail to: '[email protected]', subject: 'There is a new comment on your blog'
  end
end

Mail View

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
  </head>
  <body>
    <h1>There is a new comment on your blog</h1>
    <p> <%= @comment.content %></p>
    <p> url: <%= @url %> <p>
  </body>
</html>

纯文本版

There is a new comment on your blog

<%= @comment.content %>

url: <%= @url %>

在 Controller 中发送 Email

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new(params[:comment])
    if @comment.save
      CommentMailer.comment_notify_email(@comment).deliver
      redirect_to @post
    end
  end
end

配置

config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address              => "smtp.gmail.com",
    :port                 => 587,
    :user_name            => 'poshboytl',
    :password             =>  ENV['GMAIL_PASS'],
    :authentication       => 'plain',
    :enable_starttls_auto => true
  }

呀,国庆还没闲着啊。支持一下~!辛苦了。

#1 楼 @tassandar 哈哈 就是到了国庆才有时间做爱好的事情.... 在想还要不要再做一期 :D

@poshboytl 感谢你为初学者提供了这么好的学习资料,谢谢你

一目了然,喜欢

谢谢各位... 顺便有个东西忘了在文字部分强调,但是在视频里有所强调。 发邮件在 controller 里或者是 observer 里发 不要在 after_create 里发哟 :D

一直觉得声音超级耳熟。。。刚刚突然想起,很像一个专门讲解极限运动的电视讲解员,(偶尔在深圳卫视看到的,什么极限滑板,花式单车,那些的)博主有空可以看看。

#8 楼 @Levan 这么像?那我得找个机会听听 :D

#9 楼 @poshboytl 同学的声音超瓷性的

表示已下载,也订阅了,强力支持感觉太檑大哥的声音很吸引人,尤其是那句“shit , honeyshit😄

@poshboytl 每次看到 2 分钟左右就停止

#12 楼 @luckyyang 恩?不会吧... 难道是网络问题?你下载试试呢?

@poshboytl mark,感谢 :D

一定要看看

#13 楼 @poshboytl 今天看了下,还是不行,难道需要翻墙?优酷就没事。

#16 楼 @luckyyang 这个视频在国内...在又拍云.... 你是什么网络?是教育网吗?

#17 楼 @poshboytl 不是教育网阿,点击下载,跳到一个界面继续播放,不会下载。

#18 楼 @luckyyang 这个...你复制一下他 url,就可以下载了啊....

#19 楼 @poshboytl 哦哦,笨了,另存为就可以了。谢拉。

hi, 如果我是要发送一个带 execl 附件的邮件,那么 attachments['1.xls'] = File.read("#{Rails.root}/1.xls") 就可以了吗?但是我这样做了之后,接收到的文件是损坏的,为什么会是这样的?

你好,我的环境是 rails 3.2.13 ,在虚拟机中跑的,请问本机地址应该如何配置,localhost 可以吗?

爱死你了

一直都在关心 关注着 railscasts 但是它更新的真是超级慢,希望各位前辈们多录一些自己的教程上传到上面。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号