随笔-167  评论-65  文章-0  trackbacks-0

上一遍已经介绍了简单的rails发送mail 的demo,这个demo介绍rails发送text/html格式的邮件

预览:

image

步骤:

1,看我上遍的介绍安装smtp_tls,然后在environment.rb最后中添加

ActionMailer::Base.default_content_type = "text/html"

2,model

class Findpassword < ActionMailer::Base 
  def contact(recipient, subject, message)
    @subject = subject
    @recipients = recipient
    @from = 'no-reply@yourdomain.com'
    @sent_on = Time.now
      @body["title"] = 'This is title'
    @body["email"] = 'sender@yourdomain.com'
    @body["message"] = message
    @headers = {}
   # @headers = {content_type => 'text/html'}
  end
end

3,controller

class FindpasswordController < ApplicationController
  def index
      render :file => 'app\views\findpassword\index.rhtml'
   end
  def sendmail
    email = params["email"]
      recipient = email["recipient"]
      subject = email["subject"]
      message = email["message"]
    puts recipient + subject + message
    Findpassword.deliver_contact(recipient, subject, message)
    return if request.xhr?
    render :text => 'Email send successfully'
  end

end

4,view

views/findpassword/index.rhtml

<h1>Send Email</h1>
<% form_tag :action => 'sendmail' do %>
<p><label for="email_subject">Subject</label>:
<%= text_field 'email', 'subject' %></p>
<p><label for="email_recipient">Recipient</label>:
<%= text_field 'email', 'recipient' %></p>
<p><label for="email_message">Message</label><br/>
<%= text_area 'email', 'message' %></p>
<%= submit_tag "Send" %>
<%  end   %>

views/findpassword/contact.rhtml

Hi!
You are having one email message from <font color="red"><%= @email %></font><br/>
with a tilte <font color="red"><%= @title %></font><br/>
and following is the message:
<font color="red"><%= @message %></font><br/>
please visit  website:
<a href="http://www.blogjava.net/fl1429">http://www.blogjava.net/fl1429</a>
Thanks

5,发送邮件

http://localhost:3000/findpassword/index

注意点

1,使用text/html格式发送邮件,不是通过@headers起到效果的,而是通过ActionMailer::Base.default_content_type = "text/html" 配置

2,body部分可以

  @body["title"] = 'This is title'
    @body["email"] = 'sender@yourdomain.com'
    @body["message"] = message

这么写,也可以按照我上遍那样写成hash格式的

3,还记得上一遍说道@from不起到作用,我还苦于在网上没找到结果,突然我发现时如此的简单,一般邮件都自带设置发件人名称的功能(在个人账户处),例如gmail的是下图这样设置的:

image

126的是这样设置的:

image

收到邮件后就是这样了,发件人处就是现实自己设置的名称:

image



write by feng
posted on 2009-05-04 18:40 fl1429 阅读(890) 评论(2)  编辑  收藏 所属分类: Rails

评论:
# re: Rails Send Mail Demo2[未登录] 2009-05-18 19:04 | tingting
Findpassword.deliver_contact(recipient, subject, message)
我用的时候发现没有这个方法哦,只有这个deliver方法呢  回复  更多评论
  
# re: Rails Send Mail Demo2 2009-05-19 10:21 | fl1429
deliver_contact contact方法在model里,send mail调用的时候必须这么写!  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
已访问数:
free counters