我希望有一种可移植的Unix方式,以编程方式发送带附件的电子邮件。发送电子邮件的“标准”Unix方式似乎是mail(1),但似乎没有可移植的方式来指定附件。 (是的,我知道某些版本的邮件(1)有-a
或-A
选项,但这不是标准的,所以我不能依赖它。)
我将使用ruby,但我想要一个通用的解决方案,即一个特殊的ruby配置,涉及(比如说)使用Net :: SMTP并指定像SMTP服务器和c这样的细节。不应该在应用程序中,但应用程序应该发出像mail <some other stuff here>
这样的命令,系统应该从那里发送邮件(使用合适的〜/ .mailrc或其他)。
mail
命令仅在可以找到SMTP主机时才有效。有很多方法可以完成(sSMTP,Postfix,sendmail)。最“正常”的方式是在您的计算机上运行sendmail
,这意味着localhost
本身就是一个SMTP服务器。如果您没有安装sendmail
,我不知道如何自动获取SMTP配置。
因此,假设您知道SMTP服务器(本例中为localhost
),来自Tutorials Point的纯Ruby邮件附件:
require 'net/smtp'
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
filecontent = File.read(filename)
encodedcontent = [filecontent].pack("m") # base64
marker = "AUNIQUEMARKER"
body = <<EOF
This is a test email to send an attachement.
EOF
# Define the main headers.
part1 = <<EOF
From: Private Person <[email protected]>
To: A Test User <[email protected]>
Subject: Sending Attachement
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 = \"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename = "#{filename}"
#{encodedcontent}
--#{marker}--
EOF
mailtext = part1 + part2 + part3
# Let's put our code in safe area
begin
Net::SMTP.start('localhost') do |smtp|
smtp.sendmail(mailtext, '[email protected]', ['[email protected]'])
end
rescue Exception => e
print "Exception occured: " + e
end