我似乎无法弄清楚为什么在使用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
答案 0 :(得分:2)
这将解决您的问题,我测试过:
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指出它剥离了空行。如果你需要那些空行,我有三个选择:
MESSAGE_END.gsub(/^ {6}/,'')
#这有效,但如果缩进更改,则必须更新。 MESSAGE_END.lines.map{|l| l.gsub(/^\s+([^$])/,'\1')}.join
#尽管有缩进变化,但仍有效,但我们牺牲了可读性。 MESSAGE_END.gsub(/^[ ]+/,'')
#这是@stefan建议的,可能读得更好。