From f53579fcf9c6b2af4690699f15114d5cd42f6b79 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Mon, 26 Sep 2022 10:40:57 +0200 Subject: [PATCH] Closes #54 - Adds `DialAndSendWithContext()` and makes `DialAndSend()` use the new method --- client.go | 6 ++++++ client_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/client.go b/client.go index df0f8ea..9fb5301 100644 --- a/client.go +++ b/client.go @@ -542,6 +542,12 @@ func (c *Client) Reset() error { // default context.Background and sends the mail func (c *Client) DialAndSend(ml ...*Msg) error { ctx := context.Background() + return c.DialAndSendWithContext(ctx, ml...) +} + +// DialAndSendWithContext establishes a connection to the SMTP server with a +// custom context and sends the mail +func (c *Client) DialAndSendWithContext(ctx context.Context, ml ...*Msg) error { if err := c.DialWithContext(ctx); err != nil { return fmt.Errorf("dial failed: %w", err) } diff --git a/client_test.go b/client_test.go index 045ab65..d7e568a 100644 --- a/client_test.go +++ b/client_test.go @@ -653,6 +653,44 @@ func TestClient_DialSendClose(t *testing.T) { } } +// TestClient_DialAndSendWithContext tests the DialAndSendWithContext() method of Client +func TestClient_DialAndSendWithContext(t *testing.T) { + if os.Getenv("TEST_ALLOW_SEND") == "" { + t.Skipf("TEST_ALLOW_SEND is not set. Skipping mail sending test") + } + m := NewMsg() + _ = m.FromFormat("go-mail Test Mailer", os.Getenv("TEST_FROM")) + _ = m.To(TestRcpt) + m.Subject(fmt.Sprintf("This is a test mail from go-mail/v%s", VERSION)) + m.SetBulk() + m.SetDate() + m.SetMessageID() + m.SetBodyString(TypeTextPlain, "This is a test mail from the go-mail library") + + tests := []struct { + name string + to time.Duration + sf bool + }{ + {"Timeout: 100s", time.Second * 100, false}, + {"Timeout: 100ms", time.Millisecond * 100, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c, err := getTestConnection(true) + if err != nil { + t.Skipf("failed to create test client: %s. Skipping tests", err) + } + + ctx, cfn := context.WithTimeout(context.Background(), tt.to) + defer cfn() + if err := c.DialAndSendWithContext(ctx, m); err != nil && !tt.sf { + t.Errorf("DialAndSendWithContext() failed: %s", err) + } + }) + } +} + // TestClient_DialAndSend tests the DialAndSend() method of Client func TestClient_DialAndSend(t *testing.T) { if os.Getenv("TEST_ALLOW_SEND") == "" {