【问题标题】:Sending an HTML email with an attachment发送带有附件的 HTML 电子邮件
【发布时间】:2013-11-26 20:45:29
【问题描述】:

我有一个关于net/smtp的问题

对于 html 电子邮件,您必须在电子邮件的标题中进行设置 content-type: text/html 。但是,如果您想发送附件,您必须将其更改为content-type: multipart/mixed。这将使 html 电子邮件...不再是 html。

所以问题是.. 我如何同时完成这两个任务? HTML 和附件?

谢谢

【问题讨论】:

    标签: ruby email mime email-attachments


    【解决方案1】:

    每个附件都有自己的 MIME 类型

    多部分电子邮件的每个部分都有自己的 MIME 类型。因此,虽然电子邮件的内容类型是“多部分/混合”,但每个附件都有自己的 MIME 类型(文本、HTML 等)。

    以下是 Doug Steinwand 来自MIME and HTML in Email 的多部分电子邮件示例:

    To: whoever@someplace.com
    Subject: MIME test
    Content-type: multipart/mixed; boundary="theBoundaryString"
    
    --theBoundaryString
    
    Plain text message goes in this part. Notice that it
    has a blank line before it starts, meaning that this
    part has no additional headers.
    
    --theBoundaryString
    Content-Type: text/html
    Content-Transfer-Encoding: 7bit
    Content-Disposition: inline
    Content-Base: "http://somewebsite.com/"
    
    <body><font size=4>This</font> is a 
    <i>test</i>.
    --theBoundaryString--
    

    在这里您可以看到文本附件没有明确的内容类型。当附件没有明确的内容类型时,它是 US ASCII TEXT。 HTML 附件的内容类型为“text/html”。可能还有其他附件,每个附件都有自己的 MIME 类型。

    考虑使用“邮件”宝石

    mail gem 使发送和解析多部分电子邮件变得非常容易。它稳定,维护良好,应用广泛。

    README 中的这个示例展示了如何发送包含文本部分和 HTML 部分的多部分邮件:

    mail = Mail.deliver do
      to      'nicolas@test.lindsaar.net.au'
      from    'Mikel Lindsaar <mikel@test.lindsaar.net.au>'
      subject 'First multipart email sent with Mail'
    
      text_part do
        body 'This is plain text'
      end
    
      html_part do
        content_type 'text/html; charset=UTF-8'
        body '<h1>This is HTML</h1>'
      end
    end
    

    【讨论】:

    • 当我添加附件时,比如“add_file csv_file”,只有附件显示在电子邮件客户端中,没有纯文本或 html。当我删除 html 和文本部分,并简单地做 body “body here”时,它会正确显示文本和附件。想法?
    • 它实际上在 gmail 中正确显示,但在 Apple Mail 中却没有。我认为这个错误记录在这里:github.com/mikel/mail/issues/590。我去看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多