-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathemail-forwarder.go
122 lines (102 loc) · 2.55 KB
/
email-forwarder.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"flag"
"fmt"
"os"
"github.com/catuss-a/imap"
"github.com/keighl/mandrill"
"github.com/streadway/amqp"
)
func fatalOnError(err error, msg string) {
if err != nil {
fmt.Fprintln(os.Stderr, "%s: %s", msg, err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}
type WorkerConfig struct {
Environment string
Amqp struct {
Hostname string
MessageQueue string
}
Mandrill struct {
ClientKey string
From string
}
}
const (
defaultConfigFile = "./config.yaml"
)
var (
cfg WorkerConfig
)
func init() {
configPath := flag.String("config", defaultConfigFile, "path to the configuration file.")
flag.Parse()
fmt.Println("Loading configuration file", *configPath)
loadConfig(*configPath, &cfg)
}
func main() {
conn, err := amqp.Dial(cfg.Amqp.Hostname)
fatalOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
fatalOnError(err, "Failed to open a channel")
defer ch.Close()
fmt.Println("Queue Name:", cfg.Amqp.MessageQueue)
q, err := ch.QueueDeclare(
cfg.Amqp.MessageQueue, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
fatalOnError(err, "Failed to declare a queue")
err = ch.Qos(
1, // prefetch count
0, // prefetch size
false, // global
)
fatalOnError(err, "Failed to set QoS")
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
fatalOnError(err, "Failed to register a consumer")
forever := make(chan bool)
go func() {
mclient := mandrill.ClientWithKey(cfg.Mandrill.ClientKey)
fmt.Println("Waiting for new incoming messages to consume...")
for rawMsg := range msgs {
fmt.Println("Consuming incoming message...")
decodedMsg := imapClient.NewMessageFromBytes(rawMsg.Body)
forwardMessage(mclient, decodedMsg)
rawMsg.Ack(false)
fmt.Println("Waiting for new incoming messages to consume...")
}
}()
<-forever
}
func forwardMessage(mclient *mandrill.Client, message *imapClient.GoImapMessage) {
msg := &mandrill.Message{}
if cfg.Environment == "development" {
msg.AddRecipient("[email protected]", "Axel Catusse", "to")
} else {
msg.AddRecipient(message.To, "", "to")
}
msg.FromEmail = cfg.Mandrill.From
msg.Subject = message.Subject
msg.Text = message.Body
_, err := mclient.MessagesSend(msg)
if err != nil {
fmt.Fprintln(os.Stderr, "Error when forwarding message", err)
} else {
fmt.Println("Message succesfully forwarded")
}
}