github.com/gigforks/mattermost-server@v4.9.1-0.20180619094218-800d97fa55d0+incompatible/utils/mail_test.go (about)

     1  // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package utils
     5  
     6  import (
     7  	"strings"
     8  	"testing"
     9  
    10  	"net/smtp"
    11  
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  func TestMailConnectionFromConfig(t *testing.T) {
    16  	cfg, _, _, err := LoadConfig("config.json")
    17  	require.Nil(t, err)
    18  
    19  	if conn, err := ConnectToSMTPServer(cfg); err != nil {
    20  		t.Log(err)
    21  		t.Fatal("Should connect to the STMP Server")
    22  	} else {
    23  		if _, err1 := NewSMTPClient(conn, cfg); err1 != nil {
    24  			t.Log(err)
    25  			t.Fatal("Should get new smtp client")
    26  		}
    27  	}
    28  
    29  	cfg.EmailSettings.SMTPServer = "wrongServer"
    30  	cfg.EmailSettings.SMTPPort = "553"
    31  
    32  	if _, err := ConnectToSMTPServer(cfg); err == nil {
    33  		t.Log(err)
    34  		t.Fatal("Should not to the STMP Server")
    35  	}
    36  }
    37  
    38  func TestMailConnectionAdvanced(t *testing.T) {
    39  	cfg, _, _, err := LoadConfig("config.json")
    40  	require.Nil(t, err)
    41  
    42  	if conn, err := ConnectToSMTPServerAdvanced(
    43  		&SmtpConnectionInfo{
    44  			ConnectionSecurity:   cfg.EmailSettings.ConnectionSecurity,
    45  			SkipCertVerification: *cfg.EmailSettings.SkipServerCertificateVerification,
    46  			SmtpServerName:       cfg.EmailSettings.SMTPServer,
    47  			SmtpServerHost:       cfg.EmailSettings.SMTPServer,
    48  			SmtpPort:             cfg.EmailSettings.SMTPPort,
    49  		},
    50  	); err != nil {
    51  		t.Log(err)
    52  		t.Fatal("Should connect to the STMP Server")
    53  	} else {
    54  		if _, err1 := NewSMTPClientAdvanced(
    55  			conn,
    56  			GetHostnameFromSiteURL(*cfg.ServiceSettings.SiteURL),
    57  			&SmtpConnectionInfo{
    58  				ConnectionSecurity:   cfg.EmailSettings.ConnectionSecurity,
    59  				SkipCertVerification: *cfg.EmailSettings.SkipServerCertificateVerification,
    60  				SmtpServerName:       cfg.EmailSettings.SMTPServer,
    61  				SmtpServerHost:       cfg.EmailSettings.SMTPServer,
    62  				SmtpPort:             cfg.EmailSettings.SMTPPort,
    63  				Auth:                 *cfg.EmailSettings.EnableSMTPAuth,
    64  				SmtpUsername:         cfg.EmailSettings.SMTPUsername,
    65  				SmtpPassword:         cfg.EmailSettings.SMTPPassword,
    66  			},
    67  		); err1 != nil {
    68  			t.Log(err)
    69  			t.Fatal("Should get new smtp client")
    70  		}
    71  	}
    72  
    73  	if _, err := ConnectToSMTPServerAdvanced(
    74  		&SmtpConnectionInfo{
    75  			ConnectionSecurity:   cfg.EmailSettings.ConnectionSecurity,
    76  			SkipCertVerification: *cfg.EmailSettings.SkipServerCertificateVerification,
    77  			SmtpServerName:       "wrongServer",
    78  			SmtpServerHost:       "wrongServer",
    79  			SmtpPort:             "553",
    80  		},
    81  	); err == nil {
    82  		t.Log(err)
    83  		t.Fatal("Should not to the STMP Server")
    84  	}
    85  
    86  }
    87  
    88  func TestSendMailUsingConfig(t *testing.T) {
    89  	cfg, _, _, err := LoadConfig("config.json")
    90  	require.Nil(t, err)
    91  	T = GetUserTranslations("en")
    92  
    93  	var emailTo = "test@example.com"
    94  	var emailSubject = "Testing this email"
    95  	var emailBody = "This is a test from autobot"
    96  
    97  	//Delete all the messages before check the sample email
    98  	DeleteMailBox(emailTo)
    99  
   100  	if err := SendMailUsingConfig(emailTo, emailSubject, emailBody, cfg, true); err != nil {
   101  		t.Log(err)
   102  		t.Fatal("Should connect to the STMP Server")
   103  	} else {
   104  		//Check if the email was send to the right email address
   105  		var resultsMailbox JSONMessageHeaderInbucket
   106  		err := RetryInbucket(5, func() error {
   107  			var err error
   108  			resultsMailbox, err = GetMailBox(emailTo)
   109  			return err
   110  		})
   111  		if err != nil {
   112  			t.Log(err)
   113  			t.Log("No email was received, maybe due load on the server. Disabling this verification")
   114  		}
   115  		if err == nil && len(resultsMailbox) > 0 {
   116  			if !strings.ContainsAny(resultsMailbox[0].To[0], emailTo) {
   117  				t.Fatal("Wrong To recipient")
   118  			} else {
   119  				if resultsEmail, err := GetMessageFromMailbox(emailTo, resultsMailbox[0].ID); err == nil {
   120  					if !strings.Contains(resultsEmail.Body.Text, emailBody) {
   121  						t.Log(resultsEmail.Body.Text)
   122  						t.Fatal("Received message")
   123  					}
   124  				}
   125  			}
   126  		}
   127  	}
   128  }
   129  
   130  /*func TestSendMailUsingConfigAdvanced(t *testing.T) {
   131  	cfg, _, err := LoadConfig("config.json")
   132  	require.Nil(t, err)
   133  	T = GetUserTranslations("en")
   134  
   135  	var mimeTo = "test@example.com"
   136  	var smtpTo = "test2@example.com"
   137  	var from = mail.Address{Name: "Nobody", Address: "nobody@mattermost.com"}
   138  	var emailSubject = "Testing this email"
   139  	var emailBody = "This is a test from autobot"
   140  
   141  	//Delete all the messages before check the sample email
   142  	DeleteMailBox(smtpTo)
   143  
   144  	fileBackend, err := NewFileBackend(&cfg.FileSettings, true)
   145  	assert.Nil(t, err)
   146  
   147  	// create two files with the same name that will both be attached to the email
   148  	fileName := "file.txt"
   149  	filePath1 := fmt.Sprintf("test1/%s", fileName)
   150  	filePath2 := fmt.Sprintf("test2/%s", fileName)
   151  	fileContents1 := []byte("hello world")
   152  	fileContents2 := []byte("foo bar")
   153  	_, err := fileBackend.WriteFile(bytes.NewReader(fileContents1), filePath1)
   154  	assert.Nil(t, err)
   155  	_, err := fileBackend.WriteFile(bytes.NewReader(fileContents2), filePath2)
   156  	assert.Nil(t, err)
   157  	defer fileBackend.RemoveFile(filePath1)
   158  	defer fileBackend.RemoveFile(filePath2)
   159  
   160  	attachments := make([]*model.FileInfo, 2)
   161  	attachments[0] = &model.FileInfo{
   162  		Name: fileName,
   163  		Path: filePath1,
   164  	}
   165  	attachments[1] = &model.FileInfo{
   166  		Name: fileName,
   167  		Path: filePath2,
   168  	}
   169  
   170  	headers := make(map[string]string)
   171  	headers["TestHeader"] = "TestValue"
   172  
   173  	if err := SendMailUsingConfigAdvanced(mimeTo, smtpTo, from, emailSubject, emailBody, attachments, headers, cfg, true); err != nil {
   174  		t.Log(err)
   175  		t.Fatal("Should connect to the STMP Server")
   176  	} else {
   177  		//Check if the email was send to the right email address
   178  		var resultsMailbox JSONMessageHeaderInbucket
   179  		err := RetryInbucket(5, func() error {
   180  			var err error
   181  			resultsMailbox, err = GetMailBox(smtpTo)
   182  			return err
   183  		})
   184  		if err != nil {
   185  			t.Log(err)
   186  			t.Fatal("No emails found for address " + smtpTo)
   187  		}
   188  		if err == nil && len(resultsMailbox) > 0 {
   189  			if !strings.ContainsAny(resultsMailbox[0].To[0], smtpTo) {
   190  				t.Fatal("Wrong To recipient")
   191  			} else {
   192  				if resultsEmail, err := GetMessageFromMailbox(smtpTo, resultsMailbox[0].ID); err == nil {
   193  					if !strings.Contains(resultsEmail.Body.Text, emailBody) {
   194  						t.Log(resultsEmail.Body.Text)
   195  						t.Fatal("Received message")
   196  					}
   197  
   198  					// 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
   199  					assert.Equal(t, mimeTo, resultsEmail.Header["To"][0])
   200  
   201  					// verify that the MIME from address is correct - unfortunately, we can't verify the SMTP from address
   202  					assert.Equal(t, from.String(), resultsEmail.Header["From"][0])
   203  
   204  					// check that the custom mime headers came through - header case seems to get mutated
   205  					assert.Equal(t, "TestValue", resultsEmail.Header["Testheader"][0])
   206  
   207  					// ensure that the attachments were successfully sent
   208  					assert.Len(t, resultsEmail.Attachments, 2)
   209  					assert.Equal(t, fileName, resultsEmail.Attachments[0].Filename)
   210  					assert.Equal(t, fileName, resultsEmail.Attachments[1].Filename)
   211  					attachment1 := string(resultsEmail.Attachments[0].Bytes)
   212  					attachment2 := string(resultsEmail.Attachments[1].Bytes)
   213  					if attachment1 == string(fileContents1) {
   214  						assert.Equal(t, attachment2, string(fileContents2))
   215  					} else if attachment1 == string(fileContents2) {
   216  						assert.Equal(t, attachment2, string(fileContents1))
   217  					} else {
   218  						assert.Fail(t, "Unrecognized attachment contents")
   219  					}
   220  				}
   221  			}
   222  		}
   223  	}
   224  }*/
   225  
   226  func TestAuthMethods(t *testing.T) {
   227  	auth := &authChooser{
   228  		connectionInfo: &SmtpConnectionInfo{
   229  			SmtpUsername:   "test",
   230  			SmtpPassword:   "fakepass",
   231  			SmtpServerName: "fakeserver",
   232  			SmtpServerHost: "fakeserver",
   233  			SmtpPort:       "25",
   234  		},
   235  	}
   236  	tests := []struct {
   237  		desc   string
   238  		server *smtp.ServerInfo
   239  		err    string
   240  	}{
   241  		{
   242  			desc:   "auth PLAIN success",
   243  			server: &smtp.ServerInfo{Name: "fakeserver:25", Auth: []string{"PLAIN"}, TLS: true},
   244  		},
   245  		{
   246  			desc:   "auth PLAIN unencrypted connection fail",
   247  			server: &smtp.ServerInfo{Name: "fakeserver:25", Auth: []string{"PLAIN"}, TLS: false},
   248  			err:    "unencrypted connection",
   249  		},
   250  		{
   251  			desc:   "auth PLAIN wrong host name",
   252  			server: &smtp.ServerInfo{Name: "wrongServer:999", Auth: []string{"PLAIN"}, TLS: true},
   253  			err:    "wrong host name",
   254  		},
   255  		{
   256  			desc:   "auth LOGIN success",
   257  			server: &smtp.ServerInfo{Name: "fakeserver:25", Auth: []string{"LOGIN"}, TLS: true},
   258  		},
   259  		{
   260  			desc:   "auth LOGIN unencrypted connection fail",
   261  			server: &smtp.ServerInfo{Name: "wrongServer:999", Auth: []string{"LOGIN"}, TLS: true},
   262  			err:    "wrong host name",
   263  		},
   264  		{
   265  			desc:   "auth LOGIN wrong host name",
   266  			server: &smtp.ServerInfo{Name: "fakeserver:25", Auth: []string{"LOGIN"}, TLS: false},
   267  			err:    "unencrypted connection",
   268  		},
   269  	}
   270  
   271  	for i, test := range tests {
   272  		t.Run(test.desc, func(t *testing.T) {
   273  			_, _, err := auth.Start(test.server)
   274  			got := ""
   275  			if err != nil {
   276  				got = err.Error()
   277  			}
   278  			if got != test.err {
   279  				t.Errorf("%d. got error = %q; want %q", i, got, test.err)
   280  			}
   281  		})
   282  	}
   283  }