html email through SMTP?

C

Chris Morris

Anyone have a snippet or link to a snippet for setting up an email
with HTML formatting? Does it have to be a multipart MIME yada yada
with plain-text accompaniment, or can I skip that and just have html
in it and keep it simple?
 
K

Kirk Haines

Anyone have a snippet or link to a snippet for setting up an email
with HTML formatting? Does it have to be a multipart MIME yada yada
with plain-text accompaniment, or can I skip that and just have html
in it and keep it simple?

If you want it to be an HTML only email, it's trivial.

I tend to use the tmail library because it's simple and works for me.

To use it, do something similar to:


require 'tmail'

mail = TMail::Mail.new
mail.to = to_address
mail.from = from_address
mail.reply_to = reply_address
mail.subject = 'My Email'
mail.date = Time.now
mail.set_content_type = 'text','html'
mail.body = <<EMAIL
<head><title>My Mail</title></head>
<body><h1>Here is my HTML mail!</h1></body>
EMAIL

sm = IO.popen("/usr/sbin/sendmail -i -t","w+")
sm.print mail.encoded
sm.flush


Kirk Haines
 
R

rcoder

Once you have that TMail::Mail instance built, it's not much harder to
send via an SMTP server, either (which is good if you're on Windows,
where 'sendmail' usually isn't installed ;)

An example:
--
# ...create TMail::Mail object called 'mail', then...

require 'net/smtp'
from_addr = '(e-mail address removed)'
to_addr = '(e-mail address removed)'
mail_server = 'example.com'

Net::SMTP.start(mail_server, 25) do |smtp|
smtp.send_msg(mail.encoded, from_addr, to_addr)
end
 
B

Brian Candler

Anyone have a snippet or link to a snippet for setting up an email
with HTML formatting? Does it have to be a multipart MIME yada yada
with plain-text accompaniment, or can I skip that and just have html
in it and keep it simple?

You _can_ just put HTML in it, with Content-Type: text/html

However, it is polite (and strongly recommended) to send the mail as a
Multipart/Alternative, with the first part being a plaintext representation
of the mail, and the second part the HTML. That means that it can be read by
people whose mailers don't support HTML.

Regards,

Brian.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,414
Latest member
GayleWedel

Latest Threads

Top