歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Ruby 發送電子郵件

Ruby 發送電子郵件

日期:2017/3/1 10:38:23   编辑:Linux編程
使用Ruby發送電子郵件,無論是自動生成的還是人工輸入的都可以。首先你需要把郵件的信息轉換成一個單一的數組,包含了郵件的內容和附件等信息。需要引用這幾個類庫如RubyMail、Tmail、ActionMailer。因為ActionMailer依賴rails,所以用它來寫。

示例代碼如下

  1. require 'rubygems'
  2. require 'action_mailer'
  3. class SimpleMailer <ActionMailer::Base
  4. def Simple_message(recipient)
  5. from '[email protected]'
  6. recipients recipient
  7. subject '標題使用RUBY發送的第一封郵件'
  8. body '這是郵件的正文'
  9. end
  10. end

ActionMailer 有兩個自己定義的方法,一個是創建郵件 SimpleMailer.create_simple_message,另一個是發送郵件是SimpleMailer.deliver_simple_message

示例代碼如下

  1. puts SimpleMailer.create_simple_message('[email protected]')
  2. #發送人的郵箱 [email protected]
  3. #發送的目標油箱 [email protected]

然後設定發送郵箱的SMTP服務,最後發送do郵件

示例代碼如下

  1. ActionMailer::Base.server_settings ={:address =>'localhost',
  2. :port =>25,
  3. :domain =>'sohu.com'}
  4. SimpleMailer.deliver_simple_message('[email protected]')

如果你的SMTP是ISP的,也就是說包含用戶名和密碼的話

示例代碼如下

  1. ActionMailer::Base.server_settings ={:address =>'localhost',
  2. :port =>25,
  3. :domain =>'sohu.com',
  4. :user_name =>'[email protected]',
  5. :password =>'password',
  6. :authentication => :login}
  7. SimpleMailer.deliver_simple_message('[email protected]')

Copyright © Linux教程網 All Rights Reserved