I can't seem to figure out why my html isn't encoded when sending a email using net/smtp ruby. Any help would be greatly appreciated.
Here is my class:
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
Which gives me this email with no subject and the html is not encoded.
<b>This is my simple HTML message</b><br /><br />
It goes on to tell of wonderful things you can do in ruby.
However when I try to not ignore white spaces using <<MESSAGE_END
instead of <<-MESSAGE_END
I get this :
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
This will solve your problem, I tested:
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
The issue is with leading empty spaces, we get rid of them with: MESSAGE_END.gsub(/^\\s+/,'')
EDIT: That worked well on my email client but as @stefan pointed out it strips empty lines. If you need those empty lines I have three options:
MESSAGE_END.gsub(/^ {6}/,'')
# That works but you would have to update in case indentation changes. MESSAGE_END.lines.map{|l| l.gsub(/^\\s+([^$])/,'\\1')}.join
MESSAGE_END.lines.map{|l| l.gsub(/^\\s+([^$])/,'\\1')}.join
# That works despite of indentation changes, but we kinda sacrifice readability. MESSAGE_END.gsub(/^[ ]+/,'')
# That was suggested by @stefan and probably reads better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.