-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmail.rb
87 lines (67 loc) · 2.49 KB
/
mail.rb
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
76
77
78
79
80
81
82
83
84
85
86
87
# frozen_string_literal: true
usage 'mail [options] mail_path'
summary 'send a meeting invite or index via SMTP'
optional :u, :username, 'the username of the mail account used to send the mail'
class MailInvite < ::Nanoc::CLI::CommandRunner
def run
require 'net/smtp'
require 'socket'
require 'etc'
require 'fileutils'
@config = Nanoc::Int::ConfigLoader.new.new_from_cwd
# Extract arguments
if arguments.length != 1
raise Nanoc::Int::Errors::GenericTrivial, "usage: #{command.usage}"
end
mail_path = arguments[0]
if !File.exist?(mail_path)
raise(
Nanoc::Int::Errors::GenericTrivial,
"The invite was not sent because '#{mail_path}' was not found."
)
end
output_dir = @config[:output_dir]
if !File.fnmatch?("#{output_dir}/meetings/*/{index,agenda}.mail", mail_path)
raise(
Nanoc::Int::Errors::GenericTrivial,
"The invite was not sent because '#{mail_path}' is not found under " \
'the meetings output directory or is not a meeting index or invite mail.'
)
end
content_dir = @config[:data_sources][0][:content_dir]
sent_mail_path = mail_path.sub(output_dir, content_dir)
if File.exist?(sent_mail_path)
raise(
Nanoc::Int::Errors::GenericTrivial,
'The invite was not sent because it was already sent.'
)
end
# Setup notifications
Nanoc::Int::NotificationCenter.on(:file_created) do |file_path|
Nanoc::CLI::Logger.instance.file(:high, :create, file_path)
end
mail_message = File.read(mail_path)
from_address = @config[:mail][:from][/<(?<address>.*)>/, 'address']
to_address = @config[:mail][:to][/<(?<address>.*)>/, 'address']
username = options[:username] || Etc.getlogin
$stderr.puts "Enter the password for #{username}:"
password = $stdin.gets.chomp
mail_server = @config[:mail][:server]
mail_port = @config[:mail][:port]
$stderr.print "Sending mail via #{mail_server}:#{mail_port} to #{to_address}… "
smtp = Net::SMTP.new(mail_server, mail_port)
smtp.enable_starttls_auto
smtp.set_debug_output($stderr) if debug?
smtp.start(Socket.gethostname, username, password) do |service|
service.send_message(mail_message, from_address, to_address)
end
$stderr.puts 'done'
write(sent_mail_path, mail_message)
end
private
def write(filename, content)
File.write(filename, content)
Nanoc::Int::NotificationCenter.post(:file_created, filename)
end
end
runner MailInvite