ruby發送郵件的執行個體程式碼

來源:互聯網
上載者:User

例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='&lt;/font color="red"&gt;Here is the html conternt&lt;/font&gt;'

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

&nbsp;

if (ARGV.length &lt; 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"

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.