Skip to content

Instantly share code, notes, and snippets.

@rochefort
Created September 25, 2011 16:05
Show Gist options
  • Select an option

  • Save rochefort/1240764 to your computer and use it in GitHub Desktop.

Select an option

Save rochefort/1240764 to your computer and use it in GitHub Desktop.
send attached email on tmail
require 'rubygems'
require 'tmail'
require 'net/smtp'
require 'base64'
module MyProject
class AttachedEmail
SMTP_HOST = 'localhost'
def initialize
@mail = TMail::Mail.new
@mail.mime_version = '1.0'
@mail.set_content_type 'multipart', 'mixed', {'boundary' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx'}
end
def send(mail_from, mail_to, subject, body, attache_file)
@mail.from = mail_from
@mail.to = mail_to
@mail.subject = subject
@mail.date = Time.now
mail_body = TMail::Mail.new
mail_body.set_content_type 'text', 'plain', {'charset'=>'iso-2022-jp'}
mail_body.body = body
@mail.parts.push(mail_body)
attach = TMail::Mail.new
attach.body = Base64.encode64 File.open(attache_file, 'rb').read
attach.set_content_type 'text','plain', {'charset'=> 'iso-2022-jp'}
attach.set_content_disposition 'attachment','filename'=> attache_file
attach.transfer_encoding = 'base64'
@mail.parts.push(attach)
Net::SMTP.start(SMTP_HOST, 25) do |smtp|
smtp.sendmail(@mail.encoded, @mail.from, @mail.to)
end
end
end
end
if __FILE__ == $0
m = Mihn::AttachedEmail.new
mail_from = 'me@mail.com'
mail_to = 'me@mail.com'
subject = 'subject_test'
body = 'テストメールです'
attached_file = 'a.txt'
m.send(mail_from, mail_to, subject, body, attached_file)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment