Send email: Difference between revisions

1,751 bytes added ,  14 years ago
add Ruby
No edit summary
(add Ruby)
Line 78:
Howdy from a python function
</pre>
 
=={{header|Ruby}}==
Uses the {{libheader|RubyGems}}gem [http://tmail.rubyforge.org TMail]
<lang ruby>require 'base64'
require 'net/smtp'
 
require 'rubygems'
require 'tmail'
 
module SendEmail
 
def self.send_email(from, to, subject, body, options={})
opts = handle_options(options)
msg = build_email(from, to, subject, body, opts)
args = [opts[:server], opts[:port], opts[:helo], opts[:username], opts[:password], opts[:authtype]]
Net::SMTP.start(*args) do |smtp|
smtp.send_message(msg.to_s, msg.from[0], msg.to)
end
end
 
def self.handle_options(options)
opts = {:attachments => [], :server => 'localhost'}
unless options.nil?
options.each do |key, value|
# ensure keys are lower case symbols
opts[key.to_s.downcase.to_sym] = value
end
end
opts
end
 
def self.build_email(from, to, subject, body, opts)
msg = TMail::Mail.new
msg.from = from
msg.to = to
msg.subject = subject
msg.body = body
msg.cc = opts[:cc] if opts[:cc]
msg.bcc = opts[:bcc] if opts[:bcc]
# attach attachments
opts[:attachments].select {|file| File.readable?(file)}.each do |file|
attach = TMail::Mail.new
attach.body = Base64.encode64(File.read(file))
attach.transfer_encoding = 'base64'
attach.set_disposition("attachment", {:filename => file})
msg.parts << attach
end
msg
end
end
 
SendEmail.send_email(
'sender@sender.invalid',
%w{ recip1@recipient.invalid recip2@example.com },
'the subject',
"the body\nhas lines",
{
:attachments => %w{ file1 file2 file3 },
:server => 'mail.example.com',
:helo => 'sender.invalid',
:username => 'user',
:password => 'secret'
}
)</lang>
 
=={{header|Tcl}}==
Anonymous user