How to send a csv attachment with lines longer than 990 characters?

谁说胖子不能爱 提交于 2019-12-01 02:28:56

This seems to be because the SendGrid mail server is modifying the attachment content. If you send an attachment with a plain text storage mime type (e.g text/csv) it will wrap the content every 990 characters, as you observed. I think this is related to RFC 2045/821:

  1. Content-Transfer-Encoding Header Field

    Many media types which could be usefully transported via email are represented, in their "natural" format, as 8bit character or binary
    data. Such data cannot be transmitted over some transfer protocols.
    For example, RFC 821 (SMTP) restricts mail messages to 7bit US-ASCII
    data with lines no longer than 1000 characters including any trailing CRLF line separator.

    It is necessary, therefore, to define a standard mechanism for
    encoding such data into a 7bit short line format. Proper labelling
    of unencoded material in less restrictive formats for direct use over less restrictive transports is also desireable. This document
    specifies that such encodings will be indicated by a new "Content-
    Transfer-Encoding" header field. This field has not been defined by
    any previous standard.

If you send the attachment using base64 encoding instead of the default 7-bit the attachment remains unchanged (no added line breaks):

attachments['file.csv']= { :data=> ActiveSupport::Base64.encode64(@string), :encoding => 'base64' }

Could you have newlines in your data that would cause this? Check and see if

csv_for_orders(orders).lines.count == orders.count

If so, a quick/hackish fix might be changing where you call values_for_line_item(item) to values_for_line_item(item).map{|c| c.gsub(/(\r|\n)/, '')} (same for the other line_item calls).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!