Skip to content

Commit

Permalink
Merge pull request #55 from wneessen/54-context
Browse files Browse the repository at this point in the history
Closes #54
  • Loading branch information
wneessen committed Sep 26, 2022
2 parents ce257e1 + f53579f commit 664aca5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
6 changes: 6 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
38 changes: 38 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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") == "" {
Expand Down

0 comments on commit 664aca5

Please sign in to comment.