Rails邮件附件在电子邮件正文中

5

我需要发送带有附件的简单邮件。目前它可以发送邮件,但是附件在邮件正文中,就像这样。

enter image description here
--
Content-Type: text/csv;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
 filename=errors_in_address_table.csv
Content-ID: <5b0e7d6b4abff_10c12ac224c8b0d4994d@development.mail>

发送电子邮件的当前代码

saved_file = Rails.root.join('db', 'fix_db', 'errors_in_address_table.csv')
mailer = ActionMailer::Base.mail(from: 'no-replay@test.com', to: 'test@test.com', subject: 'Errors in database', body: '', content_type: 'multipart/mixed')
mailer.attachments['errors_in_address_table.csv'] = { mime_type: 'text/csv', content: File.read(saved_file) }
mailer.deliver

我花了几个小时来尝试使这个工作正常。也许一些更有经验的编码人员可以帮我。


2
我不确定你所说的“在电子邮件正文中”的意思,也许是因为你的邮件客户端将其显示为内联的形式而感到困惑?但是根据EML文件,我可以说它被存储为附件。 - siegy22
@siegy22 发送邮件后,我收到了正文部分包含此文本的电子邮件。 - MysteriousNothing
你可以上传你的邮件吗?那个 .eml 文件? - siegy22
3个回答

4
对于其他人,偶然发现这篇文章,以下内容应该适用于Rails控制台(至少在Rails 6+中):
mailer = ActionMailer::Base.new
mailer.attachments['errors_in_address_table.csv'] = File.read(saved_file)
mailer.mail(from: 'from@test.com', to: 'to@test.com', subject: 'Errors', body: '').deliver

0

我有一些不同的代码片段可供我的应用程序使用,我不确定这对你是否有用,但你可以尝试一下。

尝试替换你的代码块。

saved_file = Rails.root.join('db', 'fix_db', 'errors_in_address_table.csv')
mailer = ActionMailer::Base.mail(from: 'no-replay@test.com', to: 'test@test.com', subject: 'Errors in database', body: '', content_type: 'multipart/mixed')
mailer.attachments['errors_in_address_table.csv'] = { mime_type: 'text/csv', content: File.read(saved_file) }
mailer.deliver

使用以下代码,它更简单一些:

attachments['errors_in_address_table.csv'] = open(Rails.root.join('db', 'fix_db', 'errors_in_address_table.csv')).read
mail(from: 'no-replay@test.com', to: 'test@test.com', subject: 'Errors in database', body: '')

这真的是一种试错的方法。如果不起作用,我会删除它。

另外,您是否对您的邮件发送程序有任何看法?


不,我没有邮件发送视图。我需要尽可能简单。我能在不添加邮件发送视图的情况下完成吗? - MysteriousNothing

-1
根据所分享的描述,似乎您需要修改附件代码。
saved_file = Rails.root.join('db', 'fix_db', 'errors_in_address_table.csv')
mailer = ActionMailer::Base.mail(from: 'no-replay@test.com', to:    'test@test.com', subject: 'Errors in database', body: '', content_type: 'multipart/mixed')
mailer.attachments['errors_in_address_table.csv'] = saved_file
mailer.deliver

1
你能描述一下你改了什么以及为什么改吗? - siegy22
mailer.attachments['errors_in_address_table.csv'] = saved_file #修改了这一行 - Rohan
API没有关于这个的说明:http://api.rubyonrails.org/v5.0/classes/ActionMailer/Base.html#method-i-attachments - siegy22
如 http://api.rubyonrails.org/v5.0/classes/ActionMailer/Base.html#method-i-attachments 中所述, mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg') 需要在附件中指定文件路径。 - Rohan
是的,我也写了同样的东西。 mail.attachments ['filename.jpg'] = File.read('/path/to/filename.jpg') - Rohan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接