File: mail.rb

package info (click to toggle)
ruby-tins 1.32.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,248 kB
  • sloc: ruby: 6,659; makefile: 3
file content (75 lines) | stat: -rwxr-xr-x 1,349 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env ruby

require 'tins'
require 'net/smtp'
require 'time'

class Mail
  extend Tins::DSLAccessor
  include Tins::InstanceExec
  include Tins::MethodMissingDelegator::DelegatorModule
  include Tins::BlockSelf

  def initialize(&block)
    super block_self(&block)
    instance_exec(&block)
  end

  dsl_accessor :mail_server, ENV['MAILSERVER'] || 'mail'

  dsl_accessor :body

  if ENV['USER']
    dsl_accessor :from, ENV['USER'] + '@' + (ENV['MAILSERVER'] || 'mail')
  else
    dsl_accessor :from, 'joe@doe.com'
  end

  dsl_accessor :to,       'flori@ping.de'

  dsl_accessor :subject,  'Test Email'

  dsl_accessor :date      do Time.now.rfc2822 end

  def message_id
    key = [ ENV['HOSTNAME'] || 'localhost', $$ , Time.now ].join
    (::Digest::MD5.new << key).to_s
  end

  def msg
    [
      "From: #{from}",
      "To: #{to}",
      "Subject: #{subject}",
      "Date: #{date}",
      "Message-Id: <#{message_id}@#{mail_server}>",
      '',
      body
    ] * "\n"
  end

  def send
    ::Net::SMTP.start(mail_server, 25) do |smtp|
      smtp.send_message msg, from, to
    end
  end
end

def mail(&block)
  Mail.new(&block)
end

def prompt
  STDOUT.print "Send to? "
  STDOUT.flush
  STDIN.gets.strip
end

m = mail do
  subject subject + ': Hi!'
  if rcpt = prompt
    to      rcpt
  end
  body    "Hello, world!\n"
end
m.send