summaryrefslogtreecommitdiffstats
path: root/utils/inbucket.go
blob: 1c747cee84079422ae9dffec18218d3a15c663f8 (plain)
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
package utils

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
)

const (
	INBUCKET_HOST = "http://dockerhost:9000"
	INBUCKET_API  = "/api/v1/mailbox/"
)

// OutputJSONHeader holds the received Header to test sending emails (inbucket)
type JSONMessageHeaderInbucket []struct {
	Mailbox             string
	ID                  string `json:"Id"`
	From, Subject, Date string
	To                  []string
	Size                int
}

// OutputJSONMessage holds the received Message fto test sending emails (inbucket)
type JSONMessageInbucket struct {
	Mailbox             string
	ID                  string `json:"Id"`
	From, Subject, Date string
	Size                int
	Header              map[string][]string
	Body                struct {
		Text string
		HTML string `json:"Html"`
	}
}

func ParseEmail(email string) string {
	pos := strings.Index(email, "@")
	parsedEmail := email[0:pos]
	return parsedEmail
}

func GetMailBox(email string) (results JSONMessageHeaderInbucket, err error) {

	parsedEmail := ParseEmail(email)

	url := fmt.Sprintf("%s%s%s", INBUCKET_HOST, INBUCKET_API, parsedEmail)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}

	client := &http.Client{}

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var record JSONMessageHeaderInbucket
	if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
		fmt.Println(err)
		return nil, err
	}
	return record, nil
}

func GetMessageFromMailbox(email, id string) (results JSONMessageInbucket, err error) {

	parsedEmail := ParseEmail(email)

	var record JSONMessageInbucket

	url := fmt.Sprintf("%s%s%s/%s", INBUCKET_HOST, INBUCKET_API, parsedEmail, id)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return record, err
	}

	client := &http.Client{}

	resp, err := client.Do(req)
	if err != nil {
		return record, err
	}
	defer resp.Body.Close()

	if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
		fmt.Println(err)
		return record, err
	}
	return record, nil
}

func DeleteMailBox(email string) (err error) {

	parsedEmail := ParseEmail(email)

	url := fmt.Sprintf("%s%s%s", INBUCKET_HOST, INBUCKET_API, parsedEmail)
	req, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return err
	}

	client := &http.Client{}

	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return nil
}