2008-03-11

GmailのSMTPサーバを利用した添付ファイルを送れるメールスクリプト

#!/usr/local/bin/ruby

require 'net/smtp'
require 'rubygems'
require 'tlsmail'
require 'base64'

class GSMTP

  def initialize(username, password)
    @smtp = 'smtp.gmail.com'
    @helo = 'gmail.com'
    @username = username
    @password = password
    @from_addr = username
    @boundary = 'myboundry'
  end

  def send(to_addr, subject, text, *filepath)
    body = Array.new
    body << "From: #{@from_addr}"
    body << "To: #{to_addr}"
    body << "Subject: #{subject}"
    body << "MIME-Version: 1.0"
    body << "Content-Type: multipart/mixed; boundary=\"#{@boundary}\""
    body << ""
    body << "--#{@boundary}"
    body << 'Content-Type: text/plain; charset="iso-2022-jp"'
    body << ""
    body << "#{text}"

    filepath.each do |path|
      body << "--#{@boundary}"
      body << "Content-Type: application/octet-stream"
      body << "Content-Transfer-Encoding: base64"
      body << "Content-Disposition: attachment; filename=\"#{File.basename(path)}\""
      body << ""
      begin
        body << Base64.encode64(File.read(File.expand_path(path)))
      rescue => encode_error
        puts encode_error
        return
      end
    end

    body << "--#{@boundary}--"

    gmail = Net::SMTP.new(@smtp, 25)
    gmail.enable_tls(OpenSSL::SSL::VERIFY_NONE)
    begin
      gmail.start(@helo, @username, @password, :login) do |smtp|
        smtp.send_mail(body.join("\n"), @from_addr, to_addr)
      end
    rescue => send_error
      puts send_error
      return
    end
  end
end

mail = GSMTP.new("account@gmail.com", "password")
mail.send('to-address@somehost.com', '件名', 'ここが本文。これはテキストのみメール')
mail.send('to-address@somehost.com', '件名', '本文。以降の添付ファイルも送る', './hoge.txt', './foo.jpg')
Posted at 00:49 in | WriteBacks (0) | Edit