ruby基于SMTP发送带附件的邮件
其实w3c中已经有源码,此处整理一下
1. w3c源码(http://www.w3cschool.cc/ruby/ruby-sending-email.html)
require 'net/smtp'
filename = "/tmp/test.txt"
# 读取文件并编码为base64格式
filecontent = File.read(filename)
encodedcontent = [filecontent].pack("m") # base64
marker = "AUNIQUEMARKER"
body =<<EOF
This is a test email to send an attachement.
EOF
# 定义主要的头部信息
part1 =<<EOF
From: Private Person <me@fromdomain.net>
To: A Test User <test@todmain.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF
# 定义消息动作
part2 =<<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit
#{body}
--#{marker}
EOF
# 定义附件部分
part3 =<<EOF
Content-Type: multipart/mixed; name=\"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"
#{encodedcontent}
--#{marker}--
EOF
mailtext = part1 + part2 + part3
# 发送邮件
begin
Net::SMTP.start('localhost') do |smtp|
smtp.sendmail(mailtext, 'me@fromdomain.net',
['test@todmain.com'])
end
rescue Exception => e
print "Exception occured: " + e
end
2. 上网查找相关资料,可以得出用163邮箱发邮件的组织方式:(参考http://www.iteye.com/problems/18759)
require 'net/smtp'
filename = "C:/Users/Eif/Desktop/note.txt"
# 读取文件并编码为base64格式
filecontent = File.read(filename)
encodedcontent = [filecontent].pack("m") # base64
marker = "AUNIQUEMARKER"
body =<<EOF
This is a test email to send an attachement.
EOF
# 定义主要的头部信息
part1 =<<EOF
From: smoketesterrobot <此处填完整邮箱名(receiver@xxx.com)>
To: Admin <此处填完整邮箱名(sender@xxx.com)>
Subject: smoketesterdailyreport
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF
# 定义消息动作
part2 =<<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit
#{body}
--#{marker}
EOF
# 定义附件部分
part3 =<<EOF
Content-Type: multipart/mixed; name=\"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"
#{encodedcontent}
--#{marker}--
EOF
mailtext = part1 + part2 + part3
# 发送邮件
begin
Net::SMTP.start('smtp.163.com',
25,
'163.com',
'此处填完整邮箱名(receiver@xxx.com)',
'此处填sender邮箱的密码', :plain) do |smtp|
smtp.sendmail(mailtext, '此处填完整邮箱名(receiver@xxx.com)',
['此处填完整邮箱名(sender@xxx.com)'])
end
rescue Exception => e
print "Exception occured: " + e
end
3. 此处仅以163邮箱为例
Net::SMTP.start('smtp.163.com',
25,
'163.com',
其他邮箱可在邮箱的设置中找到SMTP相关支持
4. 若在32位机器运行,可能有问题,自行解决(part3),见:
# 读取文件并编码为base64格式
filecontent = File.read(filename)
encodedcontent = [filecontent].pack("m") # base64
# 定义附件部分
part3 =<<EOF
Content-Type: multipart/mixed; name=\"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"
#{encodedcontent}
--#{marker}--
EOF
5. 此处上传的附件路径为:
"C:/Users/Eif/Desktop/note.txt"
上传后附件名字为
CUsersEifDesktopnote.txt
有需要自行在part3中修改