You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails中无需模板实现Multipart多格式邮件发送?

手动在Rails中构建无模板的Multipart邮件

嘿,这个问题我刚好折腾过!不用模板的话,Rails其实提供了很直观的方式来手动构建Multipart邮件,主要有两种常用写法:

方法一:使用format块(推荐)

这是最简洁的写法,Rails会自动帮你处理Multipart的结构,直接在mail方法的块里分别定义不同格式的正文:

mail(to: 'a@example.com', subject: 'Hello Multipart') do |format|
  # 纯文本版本
  format.text { render plain: 'Hi there, this is the plain text version of your email!' }
  # HTML版本,注意用html_safe避免标签被转义
  format.html { render html: '<h1>Hi there!</h1><p>This is the HTML version with fancy formatting.</p>'.html_safe }
end

这样写的话,Rails会自动把邮件设置为multipart/alternative类型,邮件客户端会自动选择支持的格式显示——大部分现代客户端会优先显示HTML,纯文本客户端则会加载文本版。

方法二:手动添加part

如果你需要更精细地控制每个邮件部分的头信息(比如自定义字符集、关联附件等),可以直接用part方法手动添加每个正文部分:

mail(to: 'a@example.com', subject: 'Hello Multipart') do |mail|
  # 添加纯文本部分,指定字符集
  mail.part content_type: 'text/plain; charset=UTF-8' do |part|
    part.body = 'Hi there, this is plain text content with custom charset!'
  end

  # 添加HTML部分,指定字符集
  mail.part content_type: 'text/html; charset=UTF-8' do |part|
    part.body = '<h1>Hi there!</h1><p>This is HTML content with custom charset.</p>'.html_safe
  end
end

这种方式适合需要对每个邮件部分做特殊配置的场景,比如添加text/calendar类型的日历邀请内容,或者自定义编码规则。

另外要注意:不管用哪种方式,都不需要手动设置content_type为multipart/alternative——Rails会在检测到多个正文部分时自动帮你配置这个类型。

内容的提问来源于stack exchange,提问作者mahemoff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:12:33