Example 1
Require ' NET/SMTP '
Require ' iconv '
Def send_email (from, From_alias, to, To_alias, subject, content)
Subject_n = Iconv.conv (' utf-8 ', ' GBK ', subject)
msg = <<message_end
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
mime-version:1.0
Content-type:text/html;charset=utf-8
Subject: #{subject_n}
#{content}
Message_end
Net::smtp.start (' smtp.qq.com ',, ' qq.com ', #{qq_num}, #{passwd},: Login) do |smtp| #此处配置发送服
Service and Account
Smtp.send_message msg, from, to
End
End
Example 2
Ruby sends messages with NET::SMTP, but it does not support sending attachments directly. may be achieved by mailfactory this gem.
Install Mailfactory
Gem Install Mailfactory
Using the Mailfactory sample
Mail=mailfactory.new
mail.to=[' a@rubyer.me ', ' B@rubyer.me].join (', ') #多个收件人
Mail.from= ' from@rubyer.me '
Mail.subject= ' This is the subject '
Mail.html= ' </font color= ' red ' > Here is the HTML conternt</font> '
Mail.text= ' Please use HTML view '
Mail.attach ('/usr/local/test.file ')
Net::smtp.start (@smtp_host) do |smtp|
Smtp.send_message (mail.to_s (), from,to)
End
If found to have Chinese garbled
Create a new sendfile.rb file that enables you to send mail under the shell.
#!/usr/bin/env Ruby
Require ' NET/SMTP '
Require ' RubyGems '
Require ' mailfactory '
Def sendmail (to, subject, text, file)
Mail = mailfactory.new
mail.from= "localhost"
Mail.subject=subject
Mail.text=text
Mail.attach (file);
Mail.to = To
Net::smtp.start ("localhost") do |smtp|
Smtp.send_mail (mail.to_s (), "localhost", to)
End
End
if (argv.length < 4)
Puts "You should to use like this:sendFile.rb ' to_addr ' subject '" ' Text ' filepath ' "
Else
If File.file? ARGV[3]
SendMail (Argv[0], argv[1], argv[2], argv[3]
Puts "SendMail to #{argv[0]}, #{argv[1]}, #{argv[2]}, #{argv[3]}";
Else
Puts "File not exist:" + argv[3]
End
End
To add executable permissions to a file in a Linux environment
chmod +x sendfile.rb
Execute when sending mail
Sendfile.rb "To@rubyer.me" "title of the Mail" "Hello World" "/home/oldsong/test.file"