說到發(fā)送郵箱,相信大家都是非常熟悉的,但是我們程序員發(fā)送郵箱的方法是多種多樣的,今天武林技術(shù)頻道給大家整理了使用Ruby編寫發(fā)送郵件的程序的操作方法,希望對你有幫助!
??? new 方法有兩個參數(shù):
??? start 方法有以下參數(shù):
SMTP 對象實(shí)例化方法調(diào)用了 sendmail, 參數(shù)如下:
實(shí)例
以下提供了簡單的Ruby腳本來發(fā)送郵件:
ruby;">require 'net/smtp' message = <<MESSAGE_ENDFrom: Private Person <me@fromdomain.com>To: A Test User <test@todomain.com>Subject: SMTP e-mail test This is a test e-mail message.MESSAGE_END Net::SMTP.start('localhost') do |smtp| smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com'end
在以上實(shí)例中,你已經(jīng)設(shè)置了一個基本的電子郵件消息,注意正確的標(biāo)題格式。一個電子郵件要要From,To和Subject,文本內(nèi)容與頭部信息間需要一個空行。
使用Net::SMTP連接到本地機(jī)器上的SMTP服務(wù)器,使用send_message方法來發(fā)送郵件,方法參數(shù)為發(fā)送者郵件與接收者郵件。
如果你沒有運(yùn)行在本機(jī)上的SMTP服務(wù)器,您可以使用Net::SMTP與遠(yuǎn)程SMTP服務(wù)器進(jìn)行通信。如果使用網(wǎng)絡(luò)郵件服務(wù)(如Hotmail或雅虎郵件),您的電子郵件提供者會為您提供發(fā)送郵件服務(wù)器的詳細(xì)信息:
Net::SMTP.start('mail.your-domain.com')
以上代碼將連接主機(jī)為 mail.your-domain.com,端口號為 25的郵件服務(wù)器,如果需要填寫用戶名密碼,則代碼如下:
Net::SMTP.start('mail.your-domain.com', 25, 'localhost', 'username', 'password' :plain)
以上實(shí)例使用了指定的用戶名密碼連接到主機(jī)為 mail.your-domain.com,端口號為 25的郵件服務(wù)器。
使用 Ruby 發(fā)送 HTML 郵件
Net::SMTP同樣提供了支持發(fā)送 HTML 格式的郵件。
發(fā)送電子郵件時你可以設(shè)置MIME版本,文檔類型,字符集來發(fā)送HTML格式的郵件。
實(shí)例
以下實(shí)例用于發(fā)送 HTML 格式的郵件:
require 'net/smtp' message = <<MESSAGE_ENDFrom: Private Person <me@fromdomain.com>To: A Test User <test@todomain.com>MIME-Version: 1.0Content-type: text/htmlSubject: SMTP e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b><h1>This is headline.</h1>MESSAGE_END Net::SMTP.start('localhost') do |smtp| smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com'end
發(fā)送帶附件的郵件
如果需要發(fā)送混合內(nèi)容的電子郵件,需要設(shè)置Content-type為multipart/mixed。 這樣就可以在郵件中添加附件內(nèi)容。
附件在傳輸前需要使用 pack("m") 函數(shù)將其內(nèi)容轉(zhuǎn)為 base64 格式。
實(shí)例
以下實(shí)例將發(fā)送附件為 /tmp/test.txt 的郵件:
require 'net/smtp' filename = "/tmp/test.txt"# 讀取文件并編碼為base64格式filecontent = File.read(filename)encodedcontent = [filecontent].pack("m") # base64 marker = "AUNIQUEMARKER" body =<<EOFThis is a test email to send an attachement.EOF # 定義主要的頭部信息part1 =<<EOFFrom: Private Person <me@fromdomain.net>To: A Test User <test@todmain.com>Subject: Sending AttachementMIME-Version: 1.0Content-Type: multipart/mixed; boundary=#{marker}--#{marker}EOF # 定義消息動作part2 =<<EOFContent-Type: text/plainContent-Transfer-Encoding:8bit #{body}--#{marker}EOF # 定義附件部分part3 =<<EOFContent-Type: multipart/mixed; name=/"#{filename}/"Content-Transfer-Encoding:base64Content-Disposition: attachment; filename="#{filename}" #{encodedcontent}--#{marker}--EOF mailtext = part1 + part2 + part3 # 發(fā)送郵件begin Net::SMTP.start('localhost') do |smtp| smtp.sendmail(mailtext, 'me@fromdomain.net', ['test@todmain.com']) endrescue Exception => e print "Exception occured: " + e end
大家看完上文的使用Ruby編寫發(fā)送郵件的程序的操作方法之后,知道接下來怎么做了吧。可以操作試試看,有任何疑問記得給武林技術(shù)頻道小編留言哦!
新聞熱點(diǎn)
疑難解答
圖片精選