1
我一直在試圖弄清楚如何使用標準net/smtp將二進制附件發送到我的gmail帳戶。到目前爲止,我已經成功地安裝成功的文本文件 - (基於做了什麼別人)以下適用於這樣的:使用ruby net/smtp發送帶附件的電子郵件
#!/usr/bin/env ruby
require 'net/smtp'
addressee = '[email protected]'
server = 'smtp.gmail.com'
port = 587
account = 'ACCOUNT'
from = addressee
name = 'NAME'
domain = 'gmail.com'
subject = 'test of smtp using ruby'
body = 'Test of SMTP using Ruby.'
marker = "PART_SEPARATOR"
filename = "test-attachment"
filetext = "attachment contents"
print "Enter password for #{account}: "
password = $stdin.gets.chomp
# Define the main headers.
part1 = <<EOF
From: #{name} <#{from}>
To: <#{addressee}>
Subject: #{subject}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF
# Define the message action
part2 = <<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit
#{body}
--#{marker}
EOF
# Define the attachment section
part3 = <<EOF
Content-Type: text/plain
Content-Disposition: attachment; filename="#{File.basename(filename)}"
#{filetext}
--#{marker}--
EOF
message = part1 + part2 + part3
puts message
smtp = Net::SMTP.new server, port
smtp.enable_starttls
smtp.start(domain, account, password, :login) do
smtp.send_message message, from, addressee
end
問題是與編碼的二進制附件替換文本附件。上述下面的變化看起來應該基於什麼我已經能夠谷歌工作,但不能正確地發送附件:
#!/usr/bin/env ruby
require 'net/smtp'
addressee = '[email protected]'
server = 'smtp.gmail.com'
port = 587
account = 'ACCOUNT'
from = addressee
name = 'NAME'
domain = 'gmail.com'
subject = 'test of smtp using ruby'
body = 'Test of SMTP using Ruby.'
marker = "PART_SEPARATOR"
filename = "test-attachment"
filetext = "attachment contents"
print "Enter password for #{account}: "
password = $stdin.gets.chomp
# Encode contents into base64 format
encodedcontent = [filetext].pack("m")
# Define the main headers.
part1 = <<EOF
From: #{name} <#{from}>
To: <#{addressee}>
Subject: #{subject}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF
# Define the message action
part2 = <<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit
#{body}
--#{marker}
EOF
# Define the attachment section
part3 = <<EOF
Content-Type: multipart/mixed; name="#{File.basename(filename)}"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{File.basename(filename)}"
#{encodedcontent}
--#{marker}--
EOF
message = part1 + part2 + part3
puts message
smtp = Net::SMTP.new server, port
smtp.enable_starttls
smtp.start(domain, account, password, :login) do
smtp.send_message message, from, addressee
end
誰能告訴我什麼,我做錯了什麼?