问题
I want to implement a real simpel newsletter. Therefor I can select as much recipients I want.
To that newsletter I can attach a file. This works great for the first mail. All next mails have corrupted attachments (1 byte size).
actionmailer:
def send_newsletter(recipient,subject,content,file)
@content = content
if file
attachments[file.original_filename] = {
:content=> file.read,
:mime_type=> file.content_type
}
end
mail(:to => recipient, :template_name => "deliver_newsletter",
:subject => subject).deliver!
end
applicationcontroller:
def create
@customers = Customer.where("CHAR_LENGTH(email) > 0")
@recipients = params[:sent_to]
@subject = params[:subject]
@content = params[:content].html_safe
@file = params[:file]
if @recipients
@recipients.each do |mail_recipient|
Newsletter.send_newsletter(mail_recipient,@subject,@content,@file)
end
end
respond_to do |format|
format.html { redirect_to bills_path, notice: "everything works fine" }
end
end
and finally the form for sending newsletters:
<%= form_tag ('/newsletters'), :multipart => true do %>
<%= t 'views.newsletter.to_recipient' %>:<br>
<%= select_tag 'sent_to', options_from_collection_for_select(@customers, 'email', 'name'), :multiple => true, :class => 'sent_to' %><br><br>
<%= t 'views.newsletter.subject' %>:<br>
<%= text_field_tag 'subject' %><br><br>
<%= t 'views.newsletter.content' %>:<br>
<%= text_area_tag 'content', "".html_safe, :size=>"20x8" %><br><br>
<%= t 'views.newsletter.attachment' %>:<br>
<%= file_field_tag 'file' %><br><br>
<%= submit_tag t('views.buttons.newsletter_send_now'), :class => "btn btn-primary", :disable_with => t('views.buttons.newsletter_sending') %>
<% end %>
another small question: why is "delay" from the "delay_jobs" gem not working here? All other mails can be sent by typing "Newsletter.delay.send_newsletter(...)"
回答1:
This is probably happening because file.read
leaves you at the end of the file with nothing left to read. I would add a file_contents = file.read
in your ApplicationController, and then pass that in as an additional parameter to each send_newsletter
call, assuming the file is small.
来源:https://stackoverflow.com/questions/15667565/rails-3-sending-mail-with-attachment-corrupted-file-after-first-send