繁体   English   中英

无法获得ruby net / smtp通过电子邮件发送HTML代码

[英]Cant get ruby net/smtp to send html code via email

使用net / smtp ruby​​发送电子邮件时,我似乎无法弄清楚为什么我的html没有被编码。 任何帮助将不胜感激。

这是我的课:

class CheckAccounts

  def self.emailPwdExpire(email, name, days,  subject)
    begin
      server = 'x.x.x.x'
      from    = "NetworkAccountMgr"
      to      = "someuser@mydomain.com"
      subject = "Network Account Expiration Notice"
      message = <<-MESSAGE_END
      From: #{from}
      To: #{to}
      Subject: #{subject}
      Mime-Version: 1.0
      Content-Type: text/html
      Content-Disposition: inline

      <b>This is my simple HTML message</b><br /><br />
      It goes on to tell of wonderful things you can do in ruby.
      MESSAGE_END

      Net::SMTP.start(server, 25) do |s|
        s.send_message message, from, 'someuser@mydomain.com'
        s.finish
      end
    rescue [Net::SMTPFatalError, Net::SMTPSyntaxError]
      puts "BAD"
    end
  end

这给了我这封电子邮件,没有主题,并且html未被编码。

 <b>This is my simple HTML message</b><br /><br />
 It goes on to tell of wonderful things you can do in ruby.

但是,当我尝试使用<<MESSAGE_END而不是<<-MESSAGE_END忽略空白时,我得到了:

ldap_callback.rb:148: can't find string "MESSAGE_END" anywhere before EOF
ldap_callback.rb:64: syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
      message = <<MESSAGE_END 

我测试了,这将解决您的问题:

  message = <<-MESSAGE_END.gsub(/^\s+/,'')
  From: #{from}
  To: #{to}
  Subject: #{subject}
  Mime-Version: 1.0
  Content-Type: text/html
  Content-Disposition: inline

  <b>This is my simple HTML message</b><br /><br />
  It goes on to tell of wonderful things you can do in ruby.
  MESSAGE_END

问题在于前导空格,我们使用MESSAGE_END.gsub(/^\\s+/,'')删除它们


编辑:在我的电子邮件客户端上效果很好,但是正如@stefan指出的那样,它会删除空行。 如果您需要这些空行,我有三种选择:

  1. MESSAGE_END.gsub(/^ {6}/,'') #可行,但如果缩进发生更改,则必须进行更新。
  2. MESSAGE_END.lines.map{|l| l.gsub(/^\\s+([^$])/,'\\1')}.join MESSAGE_END.lines.map{|l| l.gsub(/^\\s+([^$])/,'\\1')}.join #尽管缩进发生了变化,但该方法仍然有效,但是我们还是牺牲了可读性。
  3. MESSAGE_END.gsub(/^[ ]+/,'') #这是@stefan提出的,可能读起来更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM