用ruby发送定时邮件

需求很简单,每天给几个邮箱发送前一天的销售数据。

 

你想用whenever?sidetiq?还是别的什么gem?

 

我选择独立一个ruby脚本,crontab自动执行。

 

baby.rb 1.56 KB
require 'active_record'
require "net/smtp"
require 'mysql2'
require 'yaml'

config = YAML::load(File.open(File.dirname(__FILE__) + "/database.yml"))
ActiveRecord::Base.establish_connection(config)

def query_data
 ## debug
 # start_time = '2014-12-23 00:00:00'
 # end_time = '2014-12-23 23:59:59'
 start_time = (Date.today - 1).to_s + ' 00:00:00'
 end_time = (Date.today - 1).to_s + ' 23:59:59'
 sql = 'SELECT sum(h.order_amount) FROM shop_order as h' +' '+\
 'where (h.status<>-10 and h.status<>0)' +' '+\
 'and (h.pay_time>= "' + start_time + '" and h.pay_time<= "' + end_time + '")' +' '+\
 'and h.order_type="normal"'
 p sql
 ActiveRecord::Base.connection.select_value sql
end

def chinese_date
 "#{(Time.now - 1.day).year}#{(Time.now - 1.day).month}#{(Time.now - 1.day).day}日"
end

def send_mail(data_user)
 from_address = "[email protected]"
 to_address = ["s—————@nipponpaint.com.cn", "w——@d——.com", "l——@d——.com"]

 mail = "Subject: 【立邦商城】" + chinese_date + "销量\r\n" +\
 "To: s————@nipponpaint.com.cn; w——@d——.com; l——@d——.com\r\n" +\
 "Dear all,\r\n" +\
 "\r\n" +\
 "立邦官方商城" + chinese_date + "的普通会员销量为:" + data_user.to_s + "元"
 Net::SMTP.start('localhost') do |smtp|
 smtp.send_mail(mail, from_address, to_address)
 end
end


puts Time.new
puts '----Job Start----'

 amount_user = query_data
 amount_user = '0' unless amount_user
 p "=>" + amount_user.to_s
 send_mail(amount_user)

puts '----Job Finished----'
puts Time.new
exit;

 

crontab -e

加上一条

45 18 * * * /usr/local/bin/ruby /var/www/mail/ontime/baby.rb

 

 

你可能感兴趣的:(Ruby)