summaryrefslogtreecommitdiffstats
path: root/services/mailservice/mail_test.go
blob: 9ad48c7030d370943bfb7acbb6f5b501c2dc5188 (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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package mailservice

import (
	"bytes"
	"fmt"
	"strings"
	"testing"

	"net/mail"
	"net/smtp"

	"github.com/mattermost/mattermost-server/model"
	"github.com/mattermost/mattermost-server/services/filesstore"
	"github.com/mattermost/mattermost-server/utils"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestMailConnectionFromConfig(t *testing.T) {
	cfg, _, _, err := utils.LoadConfig("config.json")
	require.Nil(t, err)

	if conn, err := ConnectToSMTPServer(cfg); err != nil {
		t.Log(err)
		t.Fatal("Should connect to the STMP Server")
	} else {
		if _, err1 := NewSMTPClient(conn, cfg); err1 != nil {
			t.Log(err)
			t.Fatal("Should get new smtp client")
		}
	}

	cfg.EmailSettings.SMTPServer = "wrongServer"
	cfg.EmailSettings.SMTPPort = "553"

	if _, err := ConnectToSMTPServer(cfg); err == nil {
		t.Log(err)
		t.Fatal("Should not to the STMP Server")
	}
}

func TestMailConnectionAdvanced(t *testing.T) {
	cfg, _, _, err := utils.LoadConfig("config.json")
	require.Nil(t, err)

	if conn, err := ConnectToSMTPServerAdvanced(
		&SmtpConnectionInfo{
			ConnectionSecurity:   cfg.EmailSettings.ConnectionSecurity,
			SkipCertVerification: *cfg.EmailSettings.SkipServerCertificateVerification,
			SmtpServerName:       cfg.EmailSettings.SMTPServer,
			SmtpServerHost:       cfg.EmailSettings.SMTPServer,
			SmtpPort:             cfg.EmailSettings.SMTPPort,
		},
	); err != nil {
		t.Log(err)
		t.Fatal("Should connect to the STMP Server")
	} else {
		if _, err1 := NewSMTPClientAdvanced(
			conn,
			utils.GetHostnameFromSiteURL(*cfg.ServiceSettings.SiteURL),
			&SmtpConnectionInfo{
				ConnectionSecurity:   cfg.EmailSettings.ConnectionSecurity,
				SkipCertVerification: *cfg.EmailSettings.SkipServerCertificateVerification,
				SmtpServerName:       cfg.EmailSettings.SMTPServer,
				SmtpServerHost:       cfg.EmailSettings.SMTPServer,
				SmtpPort:             cfg.EmailSettings.SMTPPort,
				Auth:                 *cfg.EmailSettings.EnableSMTPAuth,
				SmtpUsername:         cfg.EmailSettings.SMTPUsername,
				SmtpPassword:         cfg.EmailSettings.SMTPPassword,
			},
		); err1 != nil {
			t.Log(err)
			t.Fatal("Should get new smtp client")
		}
	}

	if _, err := ConnectToSMTPServerAdvanced(
		&SmtpConnectionInfo{
			ConnectionSecurity:   cfg.EmailSettings.ConnectionSecurity,
			SkipCertVerification: *cfg.EmailSettings.SkipServerCertificateVerification,
			SmtpServerName:       "wrongServer",
			SmtpServerHost:       "wrongServer",
			SmtpPort:             "553",
		},
	); err == nil {
		t.Log(err)
		t.Fatal("Should not to the STMP Server")
	}

}

func TestSendMailUsingConfig(t *testing.T) {
	cfg, _, _, err := utils.LoadConfig("config.json")
	require.Nil(t, err)
	utils.T = utils.GetUserTranslations("en")

	var emailTo = "test@example.com"
	var emailSubject = "Testing this email"
	var emailBody = "This is a test from autobot"

	//Delete all the messages before check the sample email
	DeleteMailBox(emailTo)

	if err := SendMailUsingConfig(emailTo, emailSubject, emailBody, cfg, true); err != nil {
		t.Log(err)
		t.Fatal("Should connect to the STMP Server")
	} else {
		//Check if the email was send to the right email address
		var resultsMailbox JSONMessageHeaderInbucket
		err := RetryInbucket(5, func() error {
			var err error
			resultsMailbox, err = GetMailBox(emailTo)
			return err
		})
		if err != nil {
			t.Log(err)
			t.Log("No email was received, maybe due load on the server. Disabling this verification")
		}
		if err == nil && len(resultsMailbox) > 0 {
			if !strings.ContainsAny(resultsMailbox[0].To[0], emailTo) {
				t.Fatal("Wrong To recipient")
			} else {
				if resultsEmail, err := GetMessageFromMailbox(emailTo, resultsMailbox[0].ID); err == nil {
					if !strings.Contains(resultsEmail.Body.Text, emailBody) {
						t.Log(resultsEmail.Body.Text)
						t.Fatal("Received message")
					}
				}
			}
		}
	}
}

func TestSendMailUsingConfigAdvanced(t *testing.T) {
	cfg, _, _, err := utils.LoadConfig("config.json")
	require.Nil(t, err)
	utils.T = utils.GetUserTranslations("en")

	var mimeTo = "test@example.com"
	var smtpTo = "test2@example.com"
	var from = mail.Address{Name: "Nobody", Address: "nobody@mattermost.com"}
	var emailSubject = "Testing this email"
	var emailBody = "This is a test from autobot"

	//Delete all the messages before check the sample email
	DeleteMailBox(smtpTo)

	fileBackend, err := filesstore.NewFileBackend(&cfg.FileSettings, true)
	assert.Nil(t, err)

	// create two files with the same name that will both be attached to the email
	fileName := "file.txt"
	filePath1 := fmt.Sprintf("test1/%s", fileName)
	filePath2 := fmt.Sprintf("test2/%s", fileName)
	fileContents1 := []byte("hello world")
	fileContents2 := []byte("foo bar")
	_, err = fileBackend.WriteFile(bytes.NewReader(fileContents1), filePath1)
	assert.Nil(t, err)
	_, err = fileBackend.WriteFile(bytes.NewReader(fileContents2), filePath2)
	assert.Nil(t, err)
	defer fileBackend.RemoveFile(filePath1)
	defer fileBackend.RemoveFile(filePath2)

	attachments := make([]*model.FileInfo, 2)
	attachments[0] = &model.FileInfo{
		Name: fileName,
		Path: filePath1,
	}
	attachments[1] = &model.FileInfo{
		Name: fileName,
		Path: filePath2,
	}

	headers := make(map[string]string)
	headers["TestHeader"] = "TestValue"

	if err := SendMailUsingConfigAdvanced(mimeTo, smtpTo, from, emailSubject, emailBody, attachments, headers, cfg, true); err != nil {
		t.Log(err)
		t.Fatal("Should connect to the STMP Server")
	} else {
		//Check if the email was send to the right email address
		var resultsMailbox JSONMessageHeaderInbucket
		err := RetryInbucket(5, func() error {
			var err error
			resultsMailbox, err = GetMailBox(smtpTo)
			return err
		})
		if err != nil {
			t.Log(err)
			t.Fatal("No emails found for address " + smtpTo)
		}
		if err == nil && len(resultsMailbox) > 0 {
			if !strings.ContainsAny(resultsMailbox[0].To[0], smtpTo) {
				t.Fatal("Wrong To recipient")
			} else {
				if resultsEmail, err := GetMessageFromMailbox(smtpTo, resultsMailbox[0].ID); err == nil {
					if !strings.Contains(resultsEmail.Body.Text, emailBody) {
						t.Log(resultsEmail.Body.Text)
						t.Fatal("Received message")
					}

					// verify that the To header of the email message is set to the MIME recipient, even though we got it out of the SMTP recipient's email inbox
					assert.Equal(t, mimeTo, resultsEmail.Header["To"][0])

					// verify that the MIME from address is correct - unfortunately, we can't verify the SMTP from address
					assert.Equal(t, from.String(), resultsEmail.Header["From"][0])

					// check that the custom mime headers came through - header case seems to get mutated
					assert.Equal(t, "TestValue", resultsEmail.Header["Testheader"][0])

					// ensure that the attachments were successfully sent
					assert.Len(t, resultsEmail.Attachments, 2)
					assert.Equal(t, fileName, resultsEmail.Attachments[0].Filename)
					assert.Equal(t, fileName, resultsEmail.Attachments[1].Filename)
					attachment1 := string(resultsEmail.Attachments[0].Bytes)
					attachment2 := string(resultsEmail.Attachments[1].Bytes)
					if attachment1 == string(fileContents1) {
						assert.Equal(t, attachment2, string(fileContents2))
					} else if attachment1 == string(fileContents2) {
						assert.Equal(t, attachment2, string(fileContents1))
					} else {
						assert.Fail(t, "Unrecognized attachment contents")
					}
				}
			}
		}
	}
}

func TestAuthMethods(t *testing.T) {
	auth := &authChooser{
		connectionInfo: &SmtpConnectionInfo{
			SmtpUsername:   "test",
			SmtpPassword:   "fakepass",
			SmtpServerName: "fakeserver",
			SmtpServerHost: "fakeserver",
			SmtpPort:       "25",
		},
	}
	tests := []struct {
		desc   string
		server *smtp.ServerInfo
		err    string
	}{
		{
			desc:   "auth PLAIN success",
			server: &smtp.ServerInfo{Name: "fakeserver:25", Auth: []string{"PLAIN"}, TLS: true},
		},
		{
			desc:   "auth PLAIN unencrypted connection fail",
			server: &smtp.ServerInfo{Name: "fakeserver:25", Auth: []string{"PLAIN"}, TLS: false},
			err:    "unencrypted connection",
		},
		{
			desc:   "auth PLAIN wrong host name",
			server: &smtp.ServerInfo{Name: "wrongServer:999", Auth: []string{"PLAIN"}, TLS: true},
			err:    "wrong host name",
		},
		{
			desc:   "auth LOGIN success",
			server: &smtp.ServerInfo{Name: "fakeserver:25", Auth: []string{"LOGIN"}, TLS: true},
		},
		{
			desc:   "auth LOGIN unencrypted connection fail",
			server: &smtp.ServerInfo{Name: "wrongServer:999", Auth: []string{"LOGIN"}, TLS: true},
			err:    "wrong host name",
		},
		{
			desc:   "auth LOGIN wrong host name",
			server: &smtp.ServerInfo{Name: "fakeserver:25", Auth: []string{"LOGIN"}, TLS: false},
			err:    "unencrypted connection",
		},
	}

	for i, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			_, _, err := auth.Start(test.server)
			got := ""
			if err != nil {
				got = err.Error()
			}
			if got != test.err {
				t.Errorf("%d. got error = %q; want %q", i, got, test.err)
			}
		})
	}
}