一聚教程网:一个值得你收藏的教程网站

热门教程

ruby发送邮件的实例程序代码

时间:2022-06-25 02:14:18 编辑:袖梨 来源:一聚教程网

例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 = <

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','[email protected]].join(',') #多个收件人

mail.from='[email protected]'

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 "[email protected]" "title of the mail" "hello world" "/home/oldsong/test.file"

热门栏目