Rails - ActionMailer sometimes shows attachments before the email content?

谁说我不能喝 提交于 2019-12-01 05:56:27

I had the same problem, and in my case the solution was to swap the attachment and mail lines. First attach, then call mail.

Rails 3

WRONG

def pdf_email(email, subject, pdfname, pdfpath)
  mail(:to => email, :subject => subject)
  attachments[pdfname] = File.read(pdfpath)
end

GOOD

def pdf_email(email, subject, pdfname, pdfpath)
  attachments[pdfname] = File.read(pdfpath)
  mail(:to => email, :subject => subject)
end

I know there is already an accepted answer, but switching the order of attachments[] and mail() didn't solve it for me. What is different about my situation is that I was trying to attach a text file attachment (.txt)

What works for me is setting the content_type and parts_order defaults for the mailer.

MyMailer < ActionMailer::Base

    default :from => "Awesome App <support@example.com>",
            :content_type => 'multipart/alternative',
            :parts_order => [ "text/html", "text/enriched", "text/plain", "application/pdf" ]

    def pdf_email(email, subject, pdfname, pdfpath)
      attachments[pdfname] = File.read(pdfpath)
      mail(:to => email, :subject => subject)
    end

    def txt_email(email, subject, filename, filebody)
      attachments[filename] = filebody
      mail(:to => email, :subject => subject)
    end
end

If you are trying to send an email in Rails 3 with a plain text file (.txt), trying adding :content_type and parts_order to your defaults so that the text file does not appear above the message in your email.

this is rail 2.3 code (might be slightly different in rails3)

just move you text part before attachment

recipients  to@domain.com
from      me@domain.com
subject   "some subject"
content_type  "multipart/mixed"

part "text/plain" do |p|
  p.body = render_message 'my_message' #this is template file
end

attachment "application/octet-stream" do |a|
  a.body = File.read("some_file.jpg")
  a.filename = 'name.jpg'
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!