论坛首页 编程语言技术论坛

使用ActionMailer加本机的postfix邮件服务器发送邮件

浏览 4276 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-12-25  
Rails发送邮件默认需要本机具备smtp服务。所以我在Linux上安装了一个postfix-2.4.6,安装后,使用telnet localhost 25登录并发送邮件:
# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 mail.xxxx.com ESMTP Postfix
输入握手命令ehlo localhost,回车
ehlo localhost
250-mail.xxxx.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
mail from: "Test"<xxxx@gmail.com>          
250 2.1.0 Ok
rcpt to: <xxxxxx@xxxxx.com>
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
hello, miaoxingfu.
just test!
.
250 2.0.0 Ok: queued as A910036B14
quit
221 2.0.0 Bye
Connection closed by foreign host.

查看邮箱,确实可以收到邮件。

然后我们使用rails的ActionMailer来发信测试。
首先配置environment.rb,增加:
ActionMailer::Base.delivery_method = :smtp

ActionMailer::Base.perform_deliveries = true

ActionMailer::Base.raise_delivery_errors = true

ActionMailer::Base.default_charset = "utf-8"

ActionMailer::Base.server_settings = {
:address => "mail.xxxx.com",
:port => 25,
:domain => "xxxx.com"
}

然后在项目中运行:
ruby script/generate mailer CatMailer

在models/cat_mailer.rb中增加:
  def confirm(send_at=Time.now)
     @subject = 'Good Morning!'
     @recipients = 'miaoxingfu@xxxxx.com'
     @from = 'miaoxingfu@gmail.com'
     @sent_on = send_at
     @body = {'abc' => 'miaoxingfu'}
     @header = {}
   end

然后在views/cat_mailer中构建confirm.rhtml模版:
Dear miao:
thank you.
send the mail <%= @abc %>

最后我们创建控制器:
ruby script/generate controller TestMail
在文件test_mail_controller.rb中增加如下action:
class TestMailController < ApplicationController
   def send_mail
     email = CatMailer.deliver_confirm()
     render(:text => email.to_s)
   end
end

OK,现在启动服务器,运行http://xxxx.xxxx.xxx/test_mial/send_mail

检查邮箱,信已经发出并已经收到了。

但是不知为什么,第二天系统突然不能工作了。老是报错:
Net::SMTPSyntaxError in Test mailController#send_mail
502 5.5.2 Error: command not recognized


RAILS_ROOT: /opt/myrails/config/..

Application Trace | Framework Trace | Full Trace
/usr/local/ruby/lib/ruby/1.8/net/smtp.rb:680:in `check_response'
/usr/local/ruby/lib/ruby/1.8/net/smtp.rb:653:in `getok'
#{RAILS_ROOT}/lib/smtp_tls.rb:56:in `starttls'
#{RAILS_ROOT}/lib/smtp_tls.rb:19:in `do_start'
#{RAILS_ROOT}/app/controllers/test_mail_controller.rb:4:in `send_mail'

真是莫名其妙了。不知大家有没有遇到类似问题?大家都使用什么邮件服务器呢?
   发表时间:2007-12-28  
等了好几天,也没有人回复,看来使用postfix的同学不太多或者用了也没遇到类似问题。

后来一想,我何必非要使用Rails自带的ActionMailer来发邮件呢?发不出去我也没必要非要在你一棵树上吊死不是?我直接用ruby语言调用服务器的smtp服务来发送邮件岂不是更爽?忙活了一通,邮件顺利发出。

真是“山重水复疑无路,柳暗花明又一村”呀。rails搞不定的东西,干脆尝试用ruby本身来搞。发邮件也可以使用MailFactory这个gem包来做,更加干脆和容易。
0 请登录后投票
   发表时间:2008-06-21  
但是我用'net/smtp'遇到一个问题,(我用的也是sendmail)
就是无论我的msgstr里面是否写了Subject,Gmail收到的邮件都是'No Subject'. To: 也是一样的问题。

不知道你有没有遇到过.
0 请登录后投票
   发表时间:2008-06-23  
我就用gmail的服务器发邮件,自己不用配啦,但是发给hotmail的基本收不到。
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics