Ruby Send Email


1.简单发送邮件

require 'net/smtp'
def send_email(to,opts={})
  opts[:server]      ||= 'localhost'
  opts[:from]        ||= '发件人地址'
  opts[:from_alias]  ||= '别名'
  opts[:subject]     ||= "邮件主题"
  opts[:body]        ||= "邮件正文"
 
msg = <<END_OF_MESSAGE
    From: #{opts[:from_alias]} <#{opts[:from]}>
    To: <#{to}>
    Subject: #{opts[:subject]}
    #{opts[:body]}
END_OF_MESSAGE

 
    Net::SMTP.start(opts[:server]) do |smtp|
        smtp.send_message msg, opts[:from], to    
    end
end

send_email("to@email.com")

2.发送html格式的邮件
邮件格式需要添加 Content-type: text/html,然后将body替换成想发送的html

3.发送附件

require 'net/smtp'

filename = "/home/neo/aaa"
# 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 <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


# 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; name=\"#{filename}\" #需要调整
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"

#{encodedcontent}
--#{marker}--
EOF


mailtext = part1 + part2 + part3

  Net::SMTP.start('localhost') do |smtp|
     smtp.sendmail(mailtext, 'me@fromdomain.net',
                          ['httplei@163.com'])
  end

附件的格式,正确的填写附件的格式,不然的话邮箱会认不出来

".jpg" => "image/jpg"
".png" => "image/x-png"
".gif" => "image/gif"
".pdf" => "application/pdf"
".doc" => "application/msword"
".gz" => "application/x-gzip"
".tar.gz" => "application/x-tgz"
".tar" => "application/x-tar"
".zip" => "application/zip"
".txt" => "text/plain"
".xls" => "application/vnd-ms-excel"
"其他"=> "application/octet-stream"
  1. #1 by beson on 2011/12/07 - 01:15

    附件是中文的时候 可以吗?我测试的时候发送中文附件,得到文件名是乱码,内容正确。

(will not be published)

Verify Code   If you cannot see the CheckCode image,please refresh the page again!