Mono repo -> Master (#22553)
Combines the following repositories into one: https://github.com/mattermost/mattermost-server https://github.com/mattermost/mattermost-webapp https://github.com/mattermost/focalboard https://github.com/mattermost/mattermost-plugin-playbooks
Этот коммит содержится в:
185
server/platform/shared/mail/inbucket.go
Обычный файл
185
server/platform/shared/mail/inbucket.go
Обычный файл
@@ -0,0 +1,185 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package mail
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
InbucketAPI = "/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"`
|
||||
}
|
||||
Attachments []struct {
|
||||
Filename string
|
||||
ContentType string `json:"content-type"`
|
||||
DownloadLink string `json:"download-link"`
|
||||
Bytes []byte `json:"-"`
|
||||
}
|
||||
}
|
||||
|
||||
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", getInbucketHost(), InbucketAPI, parsedEmail)
|
||||
resp, err := http.Get(url)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
}()
|
||||
|
||||
if resp.Body == nil {
|
||||
return nil, fmt.Errorf("no mailbox")
|
||||
}
|
||||
|
||||
var record JSONMessageHeaderInbucket
|
||||
err = json.NewDecoder(resp.Body).Decode(&record)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error: %w", err)
|
||||
}
|
||||
if len(record) == 0 {
|
||||
return nil, fmt.Errorf("no mailbox")
|
||||
}
|
||||
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func GetMessageFromMailbox(email, id string) (JSONMessageInbucket, error) {
|
||||
parsedEmail := ParseEmail(email)
|
||||
|
||||
var record JSONMessageInbucket
|
||||
|
||||
url := fmt.Sprintf("%s%s%s/%s", getInbucketHost(), InbucketAPI, parsedEmail, id)
|
||||
emailResponse, err := http.Get(url)
|
||||
if err != nil {
|
||||
return record, err
|
||||
}
|
||||
defer func() {
|
||||
io.Copy(io.Discard, emailResponse.Body)
|
||||
emailResponse.Body.Close()
|
||||
}()
|
||||
|
||||
if err = json.NewDecoder(emailResponse.Body).Decode(&record); err != nil {
|
||||
return record, err
|
||||
}
|
||||
|
||||
// download attachments
|
||||
if record.Attachments != nil && len(record.Attachments) > 0 {
|
||||
for i := range record.Attachments {
|
||||
var bytes []byte
|
||||
bytes, err = downloadAttachment(record.Attachments[i].DownloadLink)
|
||||
if err != nil {
|
||||
return record, err
|
||||
}
|
||||
record.Attachments[i].Bytes = make([]byte, len(bytes))
|
||||
copy(record.Attachments[i].Bytes, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
return record, err
|
||||
}
|
||||
|
||||
func downloadAttachment(url string) ([]byte, error) {
|
||||
attachmentResponse, err := http.Get(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer attachmentResponse.Body.Close()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
io.Copy(buf, attachmentResponse.Body)
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func DeleteMailBox(email string) (err error) {
|
||||
|
||||
parsedEmail := ParseEmail(email)
|
||||
|
||||
url := fmt.Sprintf("%s%s%s", getInbucketHost(), InbucketAPI, 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
|
||||
}
|
||||
|
||||
func RetryInbucket(attempts int, callback func() error) (err error) {
|
||||
for i := 0; ; i++ {
|
||||
err = callback()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if i >= (attempts - 1) {
|
||||
break
|
||||
}
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
fmt.Println("retrying...")
|
||||
}
|
||||
return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
|
||||
}
|
||||
|
||||
func getInbucketHost() (host string) {
|
||||
|
||||
inbucket_host := os.Getenv("CI_INBUCKET_HOST")
|
||||
if inbucket_host == "" {
|
||||
inbucket_host = "localhost"
|
||||
}
|
||||
|
||||
inbucket_port := os.Getenv("CI_INBUCKET_PORT")
|
||||
if inbucket_port == "" {
|
||||
inbucket_port = "9001"
|
||||
}
|
||||
return fmt.Sprintf("http://%s:%s", inbucket_host, inbucket_port)
|
||||
}
|
||||
380
server/platform/shared/mail/mail.go
Обычный файл
380
server/platform/shared/mail/mail.go
Обычный файл
@@ -0,0 +1,380 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package mail
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/mail"
|
||||
"net/smtp"
|
||||
"time"
|
||||
|
||||
"github.com/jaytaylor/html2text"
|
||||
"github.com/pkg/errors"
|
||||
gomail "gopkg.in/mail.v2"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v6/model"
|
||||
"github.com/mattermost/mattermost-server/v6/server/platform/shared/mlog"
|
||||
)
|
||||
|
||||
const (
|
||||
TLS = "TLS"
|
||||
StartTLS = "STARTTLS"
|
||||
)
|
||||
|
||||
type SMTPConfig struct {
|
||||
ConnectionSecurity string
|
||||
SkipServerCertificateVerification bool
|
||||
Hostname string
|
||||
ServerName string
|
||||
Server string
|
||||
Port string
|
||||
ServerTimeout int
|
||||
Username string
|
||||
Password string
|
||||
EnableSMTPAuth bool
|
||||
SendEmailNotifications bool
|
||||
FeedbackName string
|
||||
FeedbackEmail string
|
||||
ReplyToAddress string
|
||||
}
|
||||
|
||||
type mailData struct {
|
||||
mimeTo string
|
||||
smtpTo string
|
||||
from mail.Address
|
||||
cc string
|
||||
replyTo mail.Address
|
||||
subject string
|
||||
htmlBody string
|
||||
embeddedFiles map[string]io.Reader
|
||||
mimeHeaders map[string]string
|
||||
messageID string
|
||||
inReplyTo string
|
||||
references string
|
||||
category string
|
||||
}
|
||||
|
||||
// smtpClient is implemented by an smtp.Client. See https://golang.org/pkg/net/smtp/#Client.
|
||||
type smtpClient interface {
|
||||
Mail(string) error
|
||||
Rcpt(string) error
|
||||
Data() (io.WriteCloser, error)
|
||||
}
|
||||
|
||||
func encodeRFC2047Word(s string) string {
|
||||
return mime.BEncoding.Encode("utf-8", s)
|
||||
}
|
||||
|
||||
type authChooser struct {
|
||||
smtp.Auth
|
||||
config *SMTPConfig
|
||||
}
|
||||
|
||||
func (a *authChooser) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
||||
smtpAddress := a.config.ServerName + ":" + a.config.Port
|
||||
a.Auth = LoginAuth(a.config.Username, a.config.Password, smtpAddress)
|
||||
for _, method := range server.Auth {
|
||||
if method == "PLAIN" {
|
||||
a.Auth = smtp.PlainAuth("", a.config.Username, a.config.Password, a.config.ServerName+":"+a.config.Port)
|
||||
break
|
||||
}
|
||||
}
|
||||
return a.Auth.Start(server)
|
||||
}
|
||||
|
||||
type loginAuth struct {
|
||||
username, password, host string
|
||||
}
|
||||
|
||||
func LoginAuth(username, password, host string) smtp.Auth {
|
||||
return &loginAuth{username, password, host}
|
||||
}
|
||||
|
||||
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
||||
if !server.TLS {
|
||||
return "", nil, errors.New("unencrypted connection")
|
||||
}
|
||||
|
||||
if server.Name != a.host {
|
||||
return "", nil, errors.New("wrong host name")
|
||||
}
|
||||
|
||||
return "LOGIN", []byte{}, nil
|
||||
}
|
||||
|
||||
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
||||
if more {
|
||||
switch string(fromServer) {
|
||||
case "Username:":
|
||||
return []byte(a.username), nil
|
||||
case "Password:":
|
||||
return []byte(a.password), nil
|
||||
default:
|
||||
return nil, errors.New("Unknown fromServer")
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func ConnectToSMTPServerAdvanced(config *SMTPConfig) (net.Conn, error) {
|
||||
var conn net.Conn
|
||||
var err error
|
||||
|
||||
smtpAddress := config.Server + ":" + config.Port
|
||||
dialer := &net.Dialer{
|
||||
Timeout: time.Duration(config.ServerTimeout) * time.Second,
|
||||
}
|
||||
|
||||
if config.ConnectionSecurity == TLS {
|
||||
tlsconfig := &tls.Config{
|
||||
InsecureSkipVerify: config.SkipServerCertificateVerification,
|
||||
ServerName: config.ServerName,
|
||||
}
|
||||
|
||||
conn, err = tls.DialWithDialer(dialer, "tcp", smtpAddress, tlsconfig)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "unable to connect to the SMTP server through TLS")
|
||||
}
|
||||
} else {
|
||||
conn, err = dialer.Dial("tcp", smtpAddress)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "unable to connect to the SMTP server")
|
||||
}
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func ConnectToSMTPServer(config *SMTPConfig) (net.Conn, error) {
|
||||
return ConnectToSMTPServerAdvanced(config)
|
||||
}
|
||||
|
||||
func NewSMTPClientAdvanced(ctx context.Context, conn net.Conn, config *SMTPConfig) (*smtp.Client, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
var c *smtp.Client
|
||||
ec := make(chan error)
|
||||
go func() {
|
||||
var err error
|
||||
c, err = smtp.NewClient(conn, config.ServerName+":"+config.Port)
|
||||
if err != nil {
|
||||
ec <- err
|
||||
return
|
||||
}
|
||||
cancel()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
err := ctx.Err()
|
||||
if err != nil && err.Error() != "context canceled" {
|
||||
return nil, errors.Wrap(err, "unable to connect to the SMTP server")
|
||||
}
|
||||
case err := <-ec:
|
||||
return nil, errors.Wrap(err, "unable to connect to the SMTP server")
|
||||
}
|
||||
|
||||
if config.Hostname != "" {
|
||||
err := c.Hello(config.Hostname)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "unable to send hello message")
|
||||
}
|
||||
}
|
||||
|
||||
if config.ConnectionSecurity == StartTLS {
|
||||
tlsconfig := &tls.Config{
|
||||
InsecureSkipVerify: config.SkipServerCertificateVerification,
|
||||
ServerName: config.ServerName,
|
||||
}
|
||||
c.StartTLS(tlsconfig)
|
||||
}
|
||||
|
||||
if config.EnableSMTPAuth {
|
||||
if err := c.Auth(&authChooser{config: config}); err != nil {
|
||||
return nil, errors.Wrap(err, "authentication failed")
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewSMTPClient(ctx context.Context, conn net.Conn, config *SMTPConfig) (*smtp.Client, error) {
|
||||
return NewSMTPClientAdvanced(
|
||||
ctx,
|
||||
conn,
|
||||
config,
|
||||
)
|
||||
}
|
||||
|
||||
func TestConnection(config *SMTPConfig) error {
|
||||
conn, err := ConnectToSMTPServer(config)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unable to connect")
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
sec := config.ServerTimeout
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Duration(sec)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
c, err := NewSMTPClient(ctx, conn, config)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unable to connect")
|
||||
}
|
||||
c.Close()
|
||||
c.Quit()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func SendMailWithEmbeddedFilesUsingConfig(to, subject, htmlBody string, embeddedFiles map[string]io.Reader, config *SMTPConfig, enableComplianceFeatures bool, messageID string, inReplyTo string, references string, ccMail string, category string) error {
|
||||
fromMail := mail.Address{Name: config.FeedbackName, Address: config.FeedbackEmail}
|
||||
replyTo := mail.Address{Name: config.FeedbackName, Address: config.ReplyToAddress}
|
||||
|
||||
mail := mailData{
|
||||
mimeTo: to,
|
||||
smtpTo: to,
|
||||
from: fromMail,
|
||||
cc: ccMail,
|
||||
replyTo: replyTo,
|
||||
subject: subject,
|
||||
htmlBody: htmlBody,
|
||||
embeddedFiles: embeddedFiles,
|
||||
messageID: messageID,
|
||||
inReplyTo: inReplyTo,
|
||||
references: references,
|
||||
category: category,
|
||||
}
|
||||
|
||||
return sendMailUsingConfigAdvanced(mail, config)
|
||||
}
|
||||
|
||||
func SendMailUsingConfig(to, subject, htmlBody string, config *SMTPConfig, enableComplianceFeatures bool, messageID string, inReplyTo string, references string, ccMail, category string) error {
|
||||
return SendMailWithEmbeddedFilesUsingConfig(to, subject, htmlBody, nil, config, enableComplianceFeatures, messageID, inReplyTo, references, ccMail, category)
|
||||
}
|
||||
|
||||
// allows for sending an email with differing MIME/SMTP recipients
|
||||
func sendMailUsingConfigAdvanced(mail mailData, config *SMTPConfig) error {
|
||||
if config.Server == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
conn, err := ConnectToSMTPServer(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
sec := config.ServerTimeout
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Duration(sec)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
c, err := NewSMTPClient(ctx, conn, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.Quit()
|
||||
defer c.Close()
|
||||
|
||||
return sendMail(c, mail, time.Now(), config)
|
||||
}
|
||||
|
||||
const SendGridXSMTPAPIHeader = "X-SMTPAPI"
|
||||
|
||||
func sendMail(c smtpClient, mail mailData, date time.Time, config *SMTPConfig) error {
|
||||
mlog.Debug("sending mail", mlog.String("to", mail.smtpTo), mlog.String("subject", mail.subject))
|
||||
|
||||
htmlMessage := mail.htmlBody
|
||||
|
||||
txtBody, err := html2text.FromString(mail.htmlBody)
|
||||
if err != nil {
|
||||
mlog.Warn("Unable to convert html body to text", mlog.Err(err))
|
||||
txtBody = ""
|
||||
}
|
||||
|
||||
headers := map[string][]string{
|
||||
"From": {mail.from.String()},
|
||||
"To": {mail.mimeTo},
|
||||
"Subject": {encodeRFC2047Word(mail.subject)},
|
||||
"Content-Transfer-Encoding": {"8bit"},
|
||||
"Auto-Submitted": {"auto-generated"},
|
||||
"Precedence": {"bulk"},
|
||||
}
|
||||
|
||||
if mail.category != "" {
|
||||
sendgridHeader := fmt.Sprintf(`{"category": %q}`, mail.category)
|
||||
headers[SendGridXSMTPAPIHeader] = []string{sendgridHeader}
|
||||
}
|
||||
|
||||
if mail.replyTo.Address != "" {
|
||||
headers["Reply-To"] = []string{mail.replyTo.String()}
|
||||
}
|
||||
|
||||
if mail.cc != "" {
|
||||
headers["CC"] = []string{mail.cc}
|
||||
}
|
||||
|
||||
if mail.messageID != "" {
|
||||
headers["Message-ID"] = []string{mail.messageID}
|
||||
} else {
|
||||
randomStringLength := 16
|
||||
msgID := fmt.Sprintf("<%s-%d@%s>", model.NewRandomString(randomStringLength), time.Now().Unix(), config.Hostname)
|
||||
headers["Message-ID"] = []string{msgID}
|
||||
}
|
||||
|
||||
if mail.inReplyTo != "" {
|
||||
headers["In-Reply-To"] = []string{mail.inReplyTo}
|
||||
}
|
||||
|
||||
if mail.references != "" {
|
||||
headers["References"] = []string{mail.references}
|
||||
}
|
||||
|
||||
for k, v := range mail.mimeHeaders {
|
||||
headers[k] = []string{encodeRFC2047Word(v)}
|
||||
}
|
||||
|
||||
m := gomail.NewMessage(gomail.SetCharset("UTF-8"))
|
||||
m.SetHeaders(headers)
|
||||
m.SetDateHeader("Date", date)
|
||||
m.SetBody("text/plain", txtBody)
|
||||
m.AddAlternative("text/html", htmlMessage)
|
||||
|
||||
for name, reader := range mail.embeddedFiles {
|
||||
m.EmbedReader(name, reader)
|
||||
}
|
||||
|
||||
if err = c.Mail(mail.from.Address); err != nil {
|
||||
return errors.Wrap(err, "failed to set the from address")
|
||||
}
|
||||
|
||||
if err = c.Rcpt(mail.smtpTo); err != nil {
|
||||
return errors.Wrap(err, "failed to set the to address")
|
||||
}
|
||||
|
||||
w, err := c.Data()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to add email message data")
|
||||
}
|
||||
|
||||
_, err = m.WriteTo(w)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to write the email message")
|
||||
}
|
||||
err = w.Close()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to close connection to the SMTP server")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
423
server/platform/shared/mail/mail_test.go
Обычный файл
423
server/platform/shared/mail/mail_test.go
Обычный файл
@@ -0,0 +1,423 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package mail
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/mail"
|
||||
"net/smtp"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func getConfig() *SMTPConfig {
|
||||
server := os.Getenv("MM_EMAILSETTINGS_SMTPSERVER")
|
||||
if server == "" {
|
||||
server = "localhost"
|
||||
}
|
||||
port := os.Getenv("MM_EMAILSETTINGS_SMTPPORT")
|
||||
if port == "" {
|
||||
port = "10025"
|
||||
}
|
||||
|
||||
return &SMTPConfig{
|
||||
ConnectionSecurity: "",
|
||||
SkipServerCertificateVerification: false,
|
||||
Hostname: "localhost",
|
||||
ServerName: server,
|
||||
Server: server,
|
||||
Port: port,
|
||||
ServerTimeout: 10,
|
||||
Username: "",
|
||||
Password: "",
|
||||
EnableSMTPAuth: false,
|
||||
SendEmailNotifications: true,
|
||||
FeedbackName: "",
|
||||
FeedbackEmail: "test@example.com",
|
||||
ReplyToAddress: "test@example.com",
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailConnectionFromConfig(t *testing.T) {
|
||||
cfg := getConfig()
|
||||
|
||||
conn, err := ConnectToSMTPServer(cfg)
|
||||
require.NoError(t, err, "Should connect to the SMTP Server %v", err)
|
||||
|
||||
_, err = NewSMTPClient(context.Background(), conn, cfg)
|
||||
|
||||
require.NoError(t, err, "Should get new SMTP client")
|
||||
|
||||
cfg.Server = "wrongServer"
|
||||
cfg.Port = "553"
|
||||
|
||||
_, err = ConnectToSMTPServer(cfg)
|
||||
|
||||
require.Error(t, err, "Should not connect to the SMTP Server")
|
||||
}
|
||||
|
||||
func TestMailConnectionAdvanced(t *testing.T) {
|
||||
cfg := getConfig()
|
||||
|
||||
conn, err := ConnectToSMTPServerAdvanced(cfg)
|
||||
require.NoError(t, err, "Should connect to the SMTP Server")
|
||||
defer conn.Close()
|
||||
|
||||
_, err2 := NewSMTPClientAdvanced(context.Background(), conn, cfg)
|
||||
require.NoError(t, err2, "Should get new SMTP client")
|
||||
|
||||
l, err3 := net.Listen("tcp", "localhost:") // emulate nc -l <random-port>
|
||||
require.NoError(t, err3, "Should've open a network socket and listen")
|
||||
defer l.Close()
|
||||
|
||||
cfg = getConfig()
|
||||
cfg.Server = strings.Split(l.Addr().String(), ":")[0]
|
||||
cfg.Port = strings.Split(l.Addr().String(), ":")[1]
|
||||
cfg.ServerTimeout = 1
|
||||
|
||||
conn2, err := ConnectToSMTPServerAdvanced(cfg)
|
||||
require.NoError(t, err, "Should connect to the SMTP Server")
|
||||
defer conn2.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
cfg = getConfig()
|
||||
cfg.Server = strings.Split(l.Addr().String(), ":")[0]
|
||||
cfg.Port = strings.Split(l.Addr().String(), ":")[1]
|
||||
cfg.ServerTimeout = 1
|
||||
_, err4 := NewSMTPClientAdvanced(
|
||||
ctx,
|
||||
conn2,
|
||||
cfg,
|
||||
)
|
||||
require.Error(t, err4, "Should get a timeout get while creating a new SMTP client")
|
||||
assert.Contains(t, err4.Error(), "unable to connect to the SMTP server")
|
||||
|
||||
cfg = getConfig()
|
||||
cfg.Server = "wrongServer"
|
||||
cfg.Port = "553"
|
||||
cfg.ServerTimeout = 1
|
||||
|
||||
_, err5 := ConnectToSMTPServerAdvanced(cfg)
|
||||
require.Error(t, err5, "Should not connect to the SMTP Server")
|
||||
}
|
||||
|
||||
func TestSendMailUsingConfig(t *testing.T) {
|
||||
cfg := getConfig()
|
||||
|
||||
var emailTo = "test@example.com"
|
||||
var emailSubject = "Testing this email"
|
||||
var emailBody = "This is a test from autobot"
|
||||
var emailCC = "test@example.com"
|
||||
|
||||
//Delete all the messages before check the sample email
|
||||
DeleteMailBox(emailTo)
|
||||
|
||||
err2 := SendMailUsingConfig(emailTo, emailSubject, emailBody, cfg, true, "", "", "", emailCC, "")
|
||||
require.NoError(t, err2, "Should connect to the SMTP Server")
|
||||
|
||||
//Check if the email was send to the right email address
|
||||
var resultsMailbox JSONMessageHeaderInbucket
|
||||
err3 := RetryInbucket(5, func() error {
|
||||
var err error
|
||||
resultsMailbox, err = GetMailBox(emailTo)
|
||||
return err
|
||||
})
|
||||
if err3 != nil {
|
||||
t.Log(err3)
|
||||
t.Log("No email was received, maybe due load on the server. Skipping this verification")
|
||||
} else {
|
||||
if len(resultsMailbox) > 0 {
|
||||
require.Contains(t, resultsMailbox[0].To[0], emailTo, "Wrong To: recipient")
|
||||
resultsEmail, err := GetMessageFromMailbox(emailTo, resultsMailbox[0].ID)
|
||||
require.NoError(t, err, "Could not get message from mailbox")
|
||||
require.Contains(t, emailBody, resultsEmail.Body.Text, "Wrong received message %s", resultsEmail.Body.Text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendMailWithEmbeddedFilesUsingConfig(t *testing.T) {
|
||||
cfg := getConfig()
|
||||
|
||||
var emailTo = "test@example.com"
|
||||
var emailSubject = "Testing this email"
|
||||
var emailBody = "This is a test from autobot"
|
||||
var emailCC = "test@example.com"
|
||||
|
||||
//Delete all the messages before check the sample email
|
||||
DeleteMailBox(emailTo)
|
||||
|
||||
embeddedFiles := map[string]io.Reader{
|
||||
"test1.png": bytes.NewReader([]byte("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")),
|
||||
"test2.png": bytes.NewReader([]byte("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")),
|
||||
}
|
||||
err2 := SendMailWithEmbeddedFilesUsingConfig(emailTo, emailSubject, emailBody, embeddedFiles, cfg, true, "", "", "", emailCC, "")
|
||||
require.NoError(t, err2, "Should connect to the SMTP Server")
|
||||
|
||||
//Check if the email was send to the right email address
|
||||
var resultsMailbox JSONMessageHeaderInbucket
|
||||
err3 := RetryInbucket(5, func() error {
|
||||
var err error
|
||||
resultsMailbox, err = GetMailBox(emailTo)
|
||||
return err
|
||||
})
|
||||
if err3 != nil {
|
||||
t.Log(err3)
|
||||
t.Log("No email was received, maybe due load on the server. Skipping this verification")
|
||||
} else {
|
||||
if len(resultsMailbox) > 0 {
|
||||
require.Contains(t, resultsMailbox[0].To[0], emailTo, "Wrong To: recipient")
|
||||
resultsEmail, err := GetMessageFromMailbox(emailTo, resultsMailbox[0].ID)
|
||||
require.NoError(t, err, "Could not get message from mailbox")
|
||||
require.Contains(t, emailBody, resultsEmail.Body.Text, "Wrong received message %s", resultsEmail.Body.Text)
|
||||
// Usign the message size because the inbucket API doesn't return embedded attachments through the API
|
||||
require.Greater(t, resultsEmail.Size, 1500, "the file size should be more because the embedded attachments")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendMailUsingConfigAdvanced(t *testing.T) {
|
||||
cfg := getConfig()
|
||||
|
||||
//Delete all the messages before check the sample email
|
||||
DeleteMailBox("test2@example.com")
|
||||
|
||||
// create two files with the same name that will both be attached to the email
|
||||
file1, err := os.CreateTemp("", "*")
|
||||
require.NoError(t, err)
|
||||
defer os.Remove(file1.Name())
|
||||
file1.Write([]byte("hello world"))
|
||||
file1.Close()
|
||||
file2, err := os.CreateTemp("", "*")
|
||||
|
||||
require.NoError(t, err)
|
||||
defer os.Remove(file2.Name())
|
||||
file2.Write([]byte("foo bar"))
|
||||
file2.Close()
|
||||
|
||||
embeddedFiles := map[string]io.Reader{
|
||||
"test": bytes.NewReader([]byte("test data")),
|
||||
}
|
||||
|
||||
headers := make(map[string]string)
|
||||
headers["TestHeader"] = "TestValue"
|
||||
|
||||
mail := mailData{
|
||||
mimeTo: "test@example.com",
|
||||
smtpTo: "test2@example.com",
|
||||
from: mail.Address{Name: "Nobody", Address: "nobody@mattermost.com"},
|
||||
replyTo: mail.Address{Name: "ReplyTo", Address: "reply_to@mattermost.com"},
|
||||
subject: "Testing this email",
|
||||
htmlBody: "This is a test from autobot",
|
||||
embeddedFiles: embeddedFiles,
|
||||
mimeHeaders: headers,
|
||||
}
|
||||
|
||||
err = sendMailUsingConfigAdvanced(mail, cfg)
|
||||
require.NoError(t, err, "Should connect to the SMTP Server: %v", err)
|
||||
|
||||
//Check if the email was send to the right email address
|
||||
var resultsMailbox JSONMessageHeaderInbucket
|
||||
err = RetryInbucket(5, func() error {
|
||||
var mailErr error
|
||||
resultsMailbox, mailErr = GetMailBox(mail.smtpTo)
|
||||
return mailErr
|
||||
})
|
||||
require.NoError(t, err, "No emails found for address %s. error: %v", mail.smtpTo, err)
|
||||
require.NotEqual(t, len(resultsMailbox), 0)
|
||||
|
||||
require.Contains(t, resultsMailbox[0].To[0], mail.mimeTo, "Wrong To recipient")
|
||||
|
||||
resultsEmail, err := GetMessageFromMailbox(mail.smtpTo, resultsMailbox[0].ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Contains(t, mail.htmlBody, resultsEmail.Body.Text, "Wrong 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, mail.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, mail.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])
|
||||
}
|
||||
|
||||
func TestAuthMethods(t *testing.T) {
|
||||
auth := &authChooser{
|
||||
config: &SMTPConfig{
|
||||
Username: "test",
|
||||
Password: "fakepass",
|
||||
ServerName: "fakeserver",
|
||||
Server: "fakeserver",
|
||||
Port: "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()
|
||||
}
|
||||
assert.True(t, got == test.err, "%d. got error = %q; want %q", i, got, test.err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type mockMailer struct {
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (m *mockMailer) Mail(string) error { return nil }
|
||||
func (m *mockMailer) Rcpt(string) error { return nil }
|
||||
func (m *mockMailer) Data() (io.WriteCloser, error) { return m, nil }
|
||||
func (m *mockMailer) Write(p []byte) (int, error) {
|
||||
m.data = append(m.data, p...)
|
||||
return len(p), nil
|
||||
}
|
||||
func (m *mockMailer) Close() error { return nil }
|
||||
|
||||
func TestSendMail(t *testing.T) {
|
||||
dir, err := os.MkdirTemp(".", "mail-test-")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(dir)
|
||||
mocm := &mockMailer{}
|
||||
|
||||
testCases := map[string]struct {
|
||||
replyTo mail.Address
|
||||
messageID string
|
||||
inReplyTo string
|
||||
references string
|
||||
contains string
|
||||
notContains string
|
||||
}{
|
||||
"adds reply-to header": {
|
||||
mail.Address{Address: "foo@test.com"},
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"\r\nReply-To: <foo@test.com>\r\n",
|
||||
"",
|
||||
},
|
||||
"doesn't add reply-to header": {
|
||||
mail.Address{},
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"\r\nReply-To:",
|
||||
},
|
||||
|
||||
"adds message-id header": {
|
||||
mail.Address{},
|
||||
"<abc123@mattermost.com>",
|
||||
"",
|
||||
"",
|
||||
"\r\nMessage-ID: <abc123@mattermost.com>\r\n",
|
||||
"",
|
||||
},
|
||||
"always adds message-id header": {
|
||||
mail.Address{},
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"\r\nMessage-ID: <",
|
||||
"",
|
||||
},
|
||||
"adds in-reply-to header": {
|
||||
mail.Address{},
|
||||
"",
|
||||
"<defg456@mattermost.com>",
|
||||
"",
|
||||
"\r\nIn-Reply-To: <defg456@mattermost.com>\r\n",
|
||||
"",
|
||||
},
|
||||
"doesn't add in-reply-to header": {
|
||||
mail.Address{},
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"\r\nIn-Reply-To:",
|
||||
},
|
||||
"adds references header": {
|
||||
mail.Address{},
|
||||
"",
|
||||
"",
|
||||
"<ghi789@mattermost.com>",
|
||||
"\r\nReferences: <ghi789@mattermost.com>\r\n",
|
||||
"",
|
||||
},
|
||||
"doesn't add references header": {
|
||||
mail.Address{},
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"\r\nReferences:",
|
||||
},
|
||||
}
|
||||
|
||||
for testName, tc := range testCases {
|
||||
t.Run(testName, func(t *testing.T) {
|
||||
mail := mailData{"", "", mail.Address{}, "", tc.replyTo, "", "", nil, nil, tc.messageID, tc.inReplyTo, tc.references, ""}
|
||||
cfg := getConfig()
|
||||
err = sendMail(mocm, mail, time.Now(), cfg)
|
||||
require.NoError(t, err)
|
||||
if tc.contains != "" {
|
||||
require.Contains(t, string(mocm.data), tc.contains)
|
||||
}
|
||||
if tc.notContains != "" {
|
||||
require.NotContains(t, string(mocm.data), tc.notContains)
|
||||
}
|
||||
mocm.data = []byte{}
|
||||
})
|
||||
}
|
||||
}
|
||||
Ссылка в новой задаче
Block a user