Archive for October 21st, 2010

Sending email with ruby – TMail

http://yakinikunotare.boo.jp/orebase/index.php?Ruby/TMail
http://tmail.rubyforge.org/rdoc/classes/TMail/Mail.html

Simple email sending:

require 'NET / SMTP'
require 'TMail'
require 'base64'
 
Mail = TMail:: Mail.new
 
Mail.to = 'you@gmail.com'
Mail.from = 'me@gmail.com'
Mail.subject = 'Test Mail '
Mail.date = Time.now
Mail.Mime_Version = '1 .0 '
Mail.Set_Content_Type 'text', 'plain', {'charset'=>'UTF-8'}
Mail.Body = 'This is Test Mail . '
 
Net:: SMTP.start("smtp.yourhost.com", 587, "smtp.yourhost.com", "username", "password") do | SMTP | SMTP.sendmail(Mail.encoded, Mail .from, Mail.to)
end

Send attachments:

require 'NET / SMTP'
require 'TMail'
require 'base64'
 
# object
Mail = TMail:: Mail.new
 
Mail.to = 'you@gmail.com'
Mail.from = 'me@gmail.com'
Mail.subject = 'Test Mail'
Mail.date = Time.now
Mail.Mime_Version = '1 .0 '
Mail.Set_Content_Type 'multipart', 'mixed', {"boundary" => "Somethingspecial"}
 
# body
Mail_Body = TMail:: Mail.new
Mail_Body.Set_Content_Type 'text', 'plain', {'charset'=>'UTF-8'}
Mail_Body.Body = 'Ge almost'
Mail.Parts.push(@ Mail_Body)
 
# Attachments
Attach = TMail:: Mail.new
Attach.Body = Base64.Encode64 File.Open('foo.jpg', "rb").read
Attach.Set_Content_Type 'image','jpg','name'=>'foo.jpg'
Attach.Set_Content_Disposition ' Attachment ','filename'=>'foo.jpg'
Attach.transfer_encoding = 'base64'
 
# attach
Mail.Parts.push(Attach)
 
# send
Net:: SMTP.start("smtp.yourhost.com", 587, " smtp.yourhost.com ", "username", "password") do | SMTP | SMTP.sendmail(Mail.encoded, Mail.from, Mail.to)
end