今天来看看使用Rails发送带附件的邮件
[b]Controller[/b]
app/controllers/spam_controller.rb:
[code]
class SpamController < ApplicationController
def spam
Spammer.deliver_spam_with_attachment(params[:name],
params[:email],
params[:file])
redirect_to :action => "index"
end
end
[/code]
[b]Mailer[/b]
app/models/spammer.rb
[code]
class Spammer < ActionMailer::Base
def spam_with_attachment(name, email, file)
@subject = 'Have a Can of Spam!'
@body = {:name => name}
@recipients = email
@from = 'spam@chadfowlercom'
unless file.blank?
attachment :body => file.read, :filename => file.original_filename
end
end
end
[/code]
[b]Views[/b]
app/views/spam/index.rhtml
[code]
<%= form_tag({:action => "spam"}, :multipart => true) %>
<label for="name">Name of recipient:</label>
<%= text_field_tag "name" %><br/>
<label for="email">Email address to send to:</label>
<%= text_field_tag "email" %><br/>
<label for="file">File to upload:</label>
<%= text_field_tag "file" %><br/>
<%= submit_tag "Spam!" %>
<% end_form_tag %>
[/code]
app/views/spammer/spam_with_attachment.rhtml
[code]
Hey <%= @name %>,
I thought you'd appreciate this file.
Regards,
Chad
[/code]
[b]Controller[/b]
app/controllers/spam_controller.rb:
[code]
class SpamController < ApplicationController
def spam
Spammer.deliver_spam_with_attachment(params[:name],
params[:email],
params[:file])
redirect_to :action => "index"
end
end
[/code]
[b]Mailer[/b]
app/models/spammer.rb
[code]
class Spammer < ActionMailer::Base
def spam_with_attachment(name, email, file)
@subject = 'Have a Can of Spam!'
@body = {:name => name}
@recipients = email
@from = 'spam@chadfowlercom'
unless file.blank?
attachment :body => file.read, :filename => file.original_filename
end
end
end
[/code]
[b]Views[/b]
app/views/spam/index.rhtml
[code]
<%= form_tag({:action => "spam"}, :multipart => true) %>
<label for="name">Name of recipient:</label>
<%= text_field_tag "name" %><br/>
<label for="email">Email address to send to:</label>
<%= text_field_tag "email" %><br/>
<label for="file">File to upload:</label>
<%= text_field_tag "file" %><br/>
<%= submit_tag "Spam!" %>
<% end_form_tag %>
[/code]
app/views/spammer/spam_with_attachment.rhtml
[code]
Hey <%= @name %>,
I thought you'd appreciate this file.
Regards,
Chad
[/code]