我一直试图弄清楚如何使用标准的net / smtp将二进制附件发送到我的Gmail帐户的电子邮件。到目前为止,我已经成功地成功附加了一个文本文件 - 以下内容(基于其他人所做的)适用于此:
#!/usr/bin/env ruby
require 'net/smtp'
addressee = 'NAME@EMAIL.COM'
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 = 'NAME@EMAIL.COM'
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
谁能告诉我我做错了什么?
答案 0 :(得分:1)
我终于设法发送二进制附件 - 秘密是使用
Content-Type: application/octet-stream; name="#{filename}"
Content-Disposition: attachment; filename="#{filename}"; size=#{size}
在邮件的附件部分(第3部分)中。
另一件事,这适用于小型测试附件,但当我尝试更大的(140K)附件时,附件被截断。使用
filecontent = File.binread(pathname)
而不是
filecontent = File.read(pathname)
似乎解决了这个问题。 (我不太清楚为什么。)