Rails - 在 ActionMailer 中附上一个 CSV,它可以被读取为带有 BOM 的 UTF8

Rails - Attach a CSV that can be read as UTF8 with BOM in ActionMailer

在 ActionMailer 中,我正在尝试将数组的数组转换为 CSV 文件,并确保可以读取文件,就好像它是使用 BOM 以 UTF8 格式转换的一样。

之前,我是在Sublime Text中复制内容到一个新文件,然后点击File > Save With Encoding > UTF8 with BOM,否则字符最终会乱七八糟。

如何在通过 ActionMailer 发送内存中的 CSV 时实现相同的编码(我从不将文件写入磁盘)

这是我发送电子邮件的示例代码

class CSVMailer < ApplicationMailer
  def csv(csv_as_array_of_array,
    to:,
    cc: [],
    from: 'messages-noreply@example.com',
    reply_to: 'me@example.com',
    subject: 'Here is your CSV made with love ',
    filename: 'your_csv_made_with_love.csv'
  )
    attach_csv(csv_as_array_of_array, filename: filename)

    mail(
      to: to,
      cc: cc,
      subject: subject
    )
  end

  private

  def attach_csv(array_of_arrays, filename:)
    attachments[filename] = {
      mine_type: 'text/csv',
      content: CSV.generate(col_sep: ';') do |csv|
        array_of_arrays.each do |row|
          csv << row
        end
      end
    }
  end
end

好的,这就是我的做法,假设您要将以下数组发送到邮件程序函数

csv_as_array_of_array = [ 
  ['header1', 'header2'], 
  ['row1cell1', 'row1cell2'], 
  ...
]

一个简单的实用函数,将 UTF8 bom 添加到 csv 中就足够了

# Small utility method
def Utility.with_utf8_bom(content)
  "\uFEFF" + content
end

所以在 ActionMailer 中 class

class CSVMailer < ApplicationMailer
  # app/mailers/csv_mailer.rb
  def send_email_with_csv(csv_as_array_of_array)
    ...
    attach_csv(csv_as_array_of_array, filename: filename)
    mail(to: ...)
  end

  private

  def attach_csv(array_of_arrays, filename:)
    attachments[filename] = {
      mine_type: 'text/csv',
      content: Utility.with_utf8_bom(
        CSV.generate(col_sep: ';', encoding: Encoding::UTF_8) do |csv|
          array_of_arrays.each do |row|
            csv << row
          end
        end
      )
    }
  end