ActionMailer 在一封电子邮件中发送两种格式

ActionMailer sends both formats in a single email

这是很奇怪的行为。我在 EmployeeMailer.

中为一个动作定义了两个模板
employee_mailer/
    salary_slips.html.erb
    salary_slips.text.erb

下面是我使用的代码:

def salary_slips(salary_record)
  mail.attachments['#{@record.employee.name}'] = { mime_type: 'application/pdf', content: @record.create_pdf_file.render }
  mail to: @record.employee.official_email, subject: ['Salary Silp for', @date].join(' ')
end

问题是:在客户端,我收到一封以 .text.erb 部分开头的电子邮件,最后还包含 .html.erb 部分。

开发日志如各位:

Rendered employee_mailer/salary_slips.html.erb (4.2ms)
Rendered employee_mailer/salary_slips.text.erb (0.5ms)
Rendered employee_mailer/salary_slips.text.erb (0.5ms)

我认为它应该只渲染 .html.erb 部分。有什么方法可以让我控制,并在一封电子邮件中只发送 .html.erb 部分。

注:

我已经使用 format 块以下列方式明确说明格式:

mail to: @record.employee.official_email, subject: ['Salary Slip for', @date].join(' ') do |format|
  format.html { render 'salary_slips' }
  format.text { render 'salary_slips' }
end 

这是 ActionMailer 的默认行为 - 请参阅 http://guides.rubyonrails.org/action_mailer_basics.html#sending-multipart-emails

如果您只想呈现 HTML 部分,则必须删除 .text.erb 模板。

   class UserMailer < ApplicationMailer
     default from: 'notifications@example.com'

     def welcome_email(user)
        @user = user
        @url  = 'http://example.com/login'
        mail(to: @user.email,
        subject: 'Welcome to My Awesome Site') do |format|
        format.html { render 'another_template' }
        format.text { render text: 'Render text' }
   end
 end

结束

您可以select响应格式。更多细节 http://guides.rubyonrails.org/action_mailer_basics.html

post 的答案很奇怪,但当我将 mail.attachments 更改为 attachments 时它就解决了。这是我更改的行:

attachments['#{@record.employee.name}'] = { mime_type: 'application/pdf', content: @record.create_pdf_file.render }

现在,它只向一个收件人发送 HTML 部分,而不是纯文本部分。