ruby で gmail へ添付ファル付きメールを送る
- http://mac-memo.blogspot.com/2008/02/rubygmail.html
> Macメモ: RubyでGMAILにメール
の記事の ruby コードを試してみた。
問題なく 日本語メールも送れた。すばらしい!
mail-address, password を config.yaml で設定するなどの変更をしてみた。
$ cat config.yaml.template
gmail_address: xxxxxx@gmail.com
gmail_pass: xxxxxx
$ cat sendmail.rb
# See http://mac-memo.blogspot.com/2008/02/rubygmail.html
# > Macメモ: RubyでGMAILにメール
require 'net/smtp'
require 'rubygems'
require 'tlsmail'
require 'kconv'
require 'base64'
require 'yaml'
$KCODE = 'utf8'
# mail_address="xxxxxx@gmail.com"
# password='xxxxxx'
# GMAIL アドレス、パスワードを config.yaml に設定する
config_file = 'config.yaml'
config = YAML.load_file(config_file)
mail_address = config["gmail_address"]
password = config["gmail_pass"]
def send_with_attach(mail_address, password, from_address, to_address, mail_subject, mail_text, file_path)
port=587
helo_domain="gmail.com"
smtp_host="smtp.gmail.com"
smtpserver = Net::SMTP.new(smtp_host, port)
smtpserver.enable_tls(OpenSSL::SSL::VERIFY_NONE)
encoded = [File.open(file_path).readlines.join('')].pack('m')
message = <<EndOfMail
From: #{from_address}
To: #{to_address}
Date: #{ Time::now.strftime("%a, %d %b %Y %X %z")}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=\"boundary_string_by_landscape_mail\"
X-Mailer: imput.rb
Subject: #{mail_subject}
--boundary_string_by_landscape_mail
Content-Type: text/plain; charset=\"ISO-2022-JP\"
Content-Transfer-Encoding: 7bit
#{mail_text.tojis}
--boundary_string_by_landscape_mail
Content-Type: application/octet-stream; name=#{ file_path}
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=#{ File.basename(file_path)}
#{ encoded}
--boundary_string_by_landscape_mail--
EndOfMail
smtpserver.start('gmail.com', mail_address, password, :login) do |smtp|
smtp.send_message message, from_address, to_address
end
end
from_address = mail_address
to_address = mail_address
subject = 'TEST'
message = "This is TEST.\テストです。"
file_path = File.basename(ARGV[0])
send_with_attach(mail_address, password, from_address, to_address, subject, message, file_path)
最近のコメント