例1
require 'net/smtp'
require 'iconv'
def send_email(from, from_alias, to, to_alias, subject, content)
subject_n = Iconv.conv('utf-8','gbk',subject)
msg = <<MESSAGE_END
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
MIME-Version: 1.0
Content-type: text/html;charset=utf-8
Subject: #{subject_n}
#{content}
MESSAGE_END
Net::SMTP.start('smtp.qq.com', 25, 'qq.com', #{qq_num}, #{passwd}, :login) do |smtp| #此處配置發送服
務器及賬戶
smtp.send_message msg, from, to
end
end
例2
Ruby內建有 NET::SMTP 來發送郵件,但是它不支援直接發送附件。可能通過 MailFactory 這個gem 來實現。
安裝MailFactory
gem install mailfactory
使用MailFactory樣本
mail=MailFactory.new
mail.to=['a@rubyer.me','b@rubyer.me].join(',') #多個收件者
mail.from='from@rubyer.me'
mail.subject='This is the subject'
mail.html='</font color="red">Here is the html conternt</font>'
mail.text='please use html view'
mail.attach('/usr/local/test.file')
Net::SMTP.start(@smtp_host) do |smtp|
smtp.send_message(mail.to_s(),from,to)
end
如果發現有中文亂碼
建立一個sendFile.rb檔案,實現在Shell下發送郵件。
#!/usr/bin/env ruby
require 'net/smtp'
require 'rubygems'
require 'mailfactory'
def sendmail(to, subject, text, file)
mail = MailFactory.new
mail.from="localhost"
mail.subject=subject
mail.text=text
mail.attach(file);
mail.to = to
Net::SMTP.start("localhost") do |smtp|
smtp.send_mail(mail.to_s(), "localhost", to)
end
end
if (ARGV.length < 4)
puts "You should use like this: sendFile.rb 'to_addr' 'subject' 'text' 'filepath'"
else
if File.file?ARGV[3]
sendmail(ARGV[0], ARGV[1], ARGV[2], ARGV[3])
puts "sendmail to #{ARGV[0]}, #{ARGV[1]}, #{ARGV[2]}, #{ARGV[3]}";
else
puts "file not exist:" + ARGV[3]
end
end
在Linux環境下,還要對檔案添加可執行許可權
chmod +x sendFile.rb
發送郵件時執行
sendFile.rb "to@rubyer.me" "title of the mail" "hello world" "/home/oldsong/test.file"