Compare commits

...

84 commits

Author SHA1 Message Date
Michael Fuchs
7da89ac3e1
Merge 46cf2ed498 into 627216425f 2024-10-01 06:26:51 +02:00
627216425f
Merge pull request #309 from wneessen/dependabot/github_actions/github/codeql-action-3.26.10
Bump github/codeql-action from 3.26.9 to 3.26.10
2024-09-30 15:42:23 +02:00
dependabot[bot]
012082978d
Bump github/codeql-action from 3.26.9 to 3.26.10
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.26.9 to 3.26.10.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](461ef6c76d...e2b3eafc8d)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-30 13:36:41 +00:00
65a91a2711
Merge pull request #307 from wneessen/feature/269_goroutineconcurrency-safety
go-mail goroutine-/thread-safety
2024-09-27 17:17:00 +02:00
c1f6ef07d4
Skip test cases when client creation fails
Updated the client creation check to skip test cases if the client cannot be created, instead of marking them as errors. This ensures tests dependent on a successful client creation do not fail unnecessarily but are instead skipped.
2024-09-27 17:09:00 +02:00
6e98d7e47d
Reduce message loop iterations and add XOAUTH2 tests
Loop iterations in `client_test.go` were reduced from 50 to 20 for efficiency. Added new tests to verify XOAUTH2 authentication support and error handling by simulating SMTP server responses.
2024-09-27 17:00:21 +02:00
8791ce5a33
Fix deferred mutex unlock in TLSConnectionState
Correct the sequence of mutex unlocking in TLSConnectionState to ensure the mutex is always released properly. This prevents potential deadlocks and ensures the function behaves as expected in a concurrent context.
2024-09-27 17:00:07 +02:00
2d98c40cb6
Add concurrent send tests for Client
Introduced TestClient_DialSendConcurrent_online and TestClient_DialSendConcurrent_local to validate concurrent sending of messages. These tests ensure that the Client's send functionality works correctly under concurrent conditions, both in an online environment and using a local test server.
2024-09-27 14:04:02 +02:00
253d065c83
Move mutex lock to sendSingleMsg method
Mutex locking was relocated from the Send method in client_120.go and client_119.go to sendSingleMsg in client.go. This ensures thread-safety specifically during the message transmission process.
2024-09-27 14:03:50 +02:00
6bd9a9c735
Refactor mutex usage for connection safety
This commit revises locking mechanism usage around connection operations to avoid potential deadlocks and improve code clarity. Specifically, defer statements were removed and explicit unlocks were added to ensure that mutexes are properly released after critical sections. This change affects several methods, including `Close`, `cmd`, `TLSConnectionState`, `UpdateDeadline`, and newly introduced locking for concurrent data writes and reads in `dataCloser`.
2024-09-27 14:03:26 +02:00
f59aa23ed8
Add mutex locking to SetTLSConfig
This change ensures that the SetTLSConfig method is thread-safe by adding a mutex lock. The lock is acquired before any changes to the TLS configuration and released afterward to prevent concurrent access issues.
2024-09-27 11:58:08 +02:00
2234f0c5bc
Remove connection field from Client struct
This commit removes the 'connection' field from the 'Client' struct and updates the related test logic accordingly. By using 'smtpClient.HasConnection()' to check for connections, code readability and maintainability are improved. All necessary test cases have been adjusted to reflect this change.
2024-09-27 11:43:22 +02:00
fdb80ad9dd
Add mutex to Client for thread-safe operations
This commit introduces a RWMutex to the Client struct in the smtp package to ensure thread-safe access to shared resources. Critical sections in methods like Close, StartTLS, and cmd are now protected with appropriate locking mechanisms. This change helps prevent potential race conditions, ensuring consistent and reliable behavior in concurrent environments.
2024-09-27 11:10:23 +02:00
fec2f2075a
Update build tags to support future Go versions
Modified the build tags to exclude Go 1.20 and above instead of targeting only Go 1.19. This change ensures the code is compatible with future versions of Go by not restricting it to a specific minor version.
2024-09-27 10:52:30 +02:00
2084526c77
Refactor Client struct to improve organization and clarity
Rearranged and grouped struct fields more logically within Client. Introduced the dialContextFunc and fallbackPort fields to enhance connection flexibility. Minor code style adjustments were also made for better readability.
2024-09-27 10:36:09 +02:00
23c71d608f
Lock mutex before checking connection in Send method
Added mutex locking in the `Send` method for both `client_120.go` and `client_119.go`. This ensures thread-safe access to the connection checks and prevents potential race conditions.
2024-09-27 10:33:28 +02:00
371b950bc7
Refactor Client struct for better readability and organization
Reordered and grouped fields in the Client struct for clarity. The reorganization separates logical groups of fields, making it easier to understand and maintain the code. This includes proper grouping of TLS parameters, DSN options, and debug settings.
2024-09-27 10:33:19 +02:00
b2c4b533d7
Merge branch 'main' into feature/269_goroutineconcurrency-safety 2024-09-27 10:26:39 +02:00
3871b2be44
Lock client connections and update deadline handling
Add mutex locking for client connections to ensure thread safety. Introduce `HasConnection` method to check active connections and `UpdateDeadline` method to handle timeout updates. Refactor connection handling in `checkConn` and `tls` methods accordingly.
2024-09-26 11:51:30 +02:00
8683917c3d
Delete connection pool implementation and tests
Remove `connpool.go` and `connpool_test.go`. This eliminates the connection pool feature from the codebase, including associated functionality and tests. The connection pool feature is much to complex and doesn't provide the benefits expected by the concurrency feature
2024-09-26 11:49:48 +02:00
077c85bea0
Merge pull request #305 from wneessen/dependabot/github_actions/sonarsource/sonarqube-scan-action-884b79409bbd464b2a59edc326a4b77dc56b2195
Bump sonarsource/sonarqube-scan-action from f885e52a7572cf7943f28637e75730227df2dbf2 to 884b79409bbd464b2a59edc326a4b77dc56b2195
2024-09-25 16:00:56 +02:00
909e699b99
Merge pull request #306 from wneessen/dependabot/github_actions/github/codeql-action-3.26.9
Bump github/codeql-action from 3.26.8 to 3.26.9
2024-09-25 16:00:44 +02:00
dependabot[bot]
b97073db19
Bump github/codeql-action from 3.26.8 to 3.26.9
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.26.8 to 3.26.9.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](294a9d9291...461ef6c76d)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-25 13:58:44 +00:00
dependabot[bot]
d75d990124
Bump sonarsource/sonarqube-scan-action
Bumps [sonarsource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action) from f885e52a7572cf7943f28637e75730227df2dbf2 to 884b79409bbd464b2a59edc326a4b77dc56b2195.
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](f885e52a75...884b79409b)

---
updated-dependencies:
- dependency-name: sonarsource/sonarqube-scan-action
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-25 13:58:36 +00:00
0676d99f20
Merge pull request #304 from wneessen/dependabot/github_actions/sonarsource/sonarqube-scan-action-f885e52a7572cf7943f28637e75730227df2dbf2
Bump sonarsource/sonarqube-scan-action from 0c0f3958d90fc466625f1d1af1f47bddd4cc6bd1 to f885e52a7572cf7943f28637e75730227df2dbf2
2024-09-24 15:50:50 +02:00
dependabot[bot]
d6725b2d63
Bump sonarsource/sonarqube-scan-action
Bumps [sonarsource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action) from 0c0f3958d90fc466625f1d1af1f47bddd4cc6bd1 to f885e52a7572cf7943f28637e75730227df2dbf2.
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](0c0f3958d9...f885e52a75)

---
updated-dependencies:
- dependency-name: sonarsource/sonarqube-scan-action
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-24 13:48:36 +00:00
fd115d5173
Remove typo from comment in smtp_ehlo_117.go
Fixed a typo in the backward compatibility comment for Go 1.16/1.17 in smtp_ehlo_117.go. This ensures clarity and correctness in documentation.
2024-09-23 14:15:43 +02:00
4f6224131e
Rename test for accurate context cancellation
Updated the test name from `TestConnPool_GetContextTimeout` to `TestConnPool_GetContextCancel` to better reflect its functionality. This change improves test readability and maintains consistency with the context usage in the test.
2024-09-23 13:46:41 +02:00
c8684886ed
Refactor Get method to include context argument
Updated the Get method in connpool.go and its usage in tests to include a context argument for better cancellation and timeout handling. Removed the redundant dialContext field from the connection pool struct and added a new test to validate context timeout behavior.
2024-09-23 13:44:03 +02:00
07e7b17ae8
Add tests for ConnPool close and concurrency issues
This commit introduces two new tests: `TestConnPool_Close` and `TestConnPool_Concurrency`. The former ensures the proper closing of connection pool resources, while the latter checks for concurrency issues by creating and closing multiple connections in parallel.
2024-09-23 11:45:22 +02:00
2abdee743d
Add unit test for marking connection as unusable
Introduces `TestPoolConn_MarkUnusable` to ensure the pool maintains its integrity when a connection is marked unusable. This test validates that the connection pool size adjusts correctly after marking a connection as unusable and closing it.
2024-09-23 11:27:05 +02:00
5503be8451
Remove redundant error print statements
Removed redundant fmt.Printf error print statements for connection read and write errors. This cleans up the test output and makes error handling more streamlined.
2024-09-23 11:26:54 +02:00
774925078a
Improve error handling in connection pool tests
Add error checks to Close() calls in connpool_test.go to ensure connection closures are handled properly, with descriptive error messages. Update comment in connpool.go to improve clarity on the source of code inspiration.
2024-09-23 11:17:58 +02:00
f1188bdad7
Add test for PoolConn Close method
This commit introduces a new test, `TestPoolConn_Close`, to verify that connections are correctly closed and returned to the pool. It sets up a simple SMTP server, creates a connection pool, tests writing to and closing connections, and checks the pool size to ensure proper behavior.
2024-09-23 11:15:56 +02:00
2cbd0c4aef
Add test cases for connection pool functionality
Added new test cases `TestConnPool_Get_Type` and `TestConnPool_Get` to verify connection pool operations. These tests ensure proper connection type and handling of pool size after connection retrieval and usage.
2024-09-23 11:09:11 +02:00
9a9e0c936d
Remove redundant error handling in test code
The check for io.EOF and the associated print statement were unnecessary because the loop breaks on any error. This change simplifies the error handling logic in the `client_test.go` file and avoids redundant code.
2024-09-23 11:09:03 +02:00
33d4eb5b21
Add unit tests for connection pool and rename Len to Size
Introduced unit tests for the connection pool to ensure robust functionality. Also, renamed the Len method to Size in the Pool interface and its implementation for better clarity and consistency.
2024-09-23 10:33:06 +02:00
d6e5034bba
Add new error handling and connection management in connpool
Introduce ErrClosed and ErrNilConn errors for better error handling. Implement Close and MarkUnusable methods for improved connection lifecycle management. Add put method to return connections to the pool or close them if necessary.
2024-09-23 10:09:38 +02:00
1394f1fc20
Add context management and error handling to connection pool
Introduced context support and enhanced error handling in connpool.go. Added detailed comments for better maintainability and introduced a wrapper for net.Conn to manage connection close behavior. The changes improve the robustness and clarity of the connection pool's operation.
2024-09-23 09:56:23 +02:00
26ff177fb0
Add connPool implementation and connection pool errors
Introduce connPool struct and implement the Pool interface. Add error handling for invalid pool capacity settings and provide a constructor for creating new connection pools with specified capacities.
2024-09-22 21:12:59 +02:00
5ec8a5a5fe
Add initial connection pool interface
Introduces a new `connpool.go` file implementing a connection pool interface for managing network connections. This interface includes methods to get and close connections, as well as to retrieve the current pool size. The implementation is initially based on a fork of code from the Fatih Arslan GitHub repository.
2024-09-22 20:48:09 +02:00
580d0b0e4e
Merge pull request #303 from wneessen/more-test-coverage
More test coverage
2024-09-20 22:21:49 +02:00
3f0ac027e2
Add test for zero input in randNum
This commit introduces a new test case in random_test.go to ensure that the randNum function returns zero when given an input of zero. This helps validate the correctness of edge case handling in the random number generation logic.
2024-09-20 22:06:11 +02:00
0b9a215e7d
Add deferred TMPDIR restoration in test setup
Store and restore the original TMPDIR value using a deferred function in `msg_nowin_test.go`. This ensures the TMPDIR environment variable is restored after the test runs, preventing potential side effects on other tests or processes.
2024-09-20 21:42:10 +02:00
4053457020
Refactor TestSendError_ErrorMulti formatting
Reformatted the instantiation of the SendError struct to improve readability. This helps maintain consistency and clarity in the code base for better collaboration and future maintenance.
2024-09-20 21:15:13 +02:00
f3633e1913
Add tests for SendError functionalities
Introduce tests for `SendError` to verify behavior of `errors.Is` and string representation. `TestSendError_IsFail` checks for error mismatch, and `TestSendError_ErrorMulti` verifies the formatted error message.
2024-09-20 21:11:19 +02:00
52061f97c6
Add tests for nil SendError MessageID and Msg
These tests ensure that accessing MessageID and Msg methods on a nil SendError pointer returns the expected values (empty string and nil respectively). This helps in validating the error handling logic and avoiding potential nil pointer dereference issues.
2024-09-20 20:58:29 +02:00
77920be1a1
Remove unnecessary error handling
Eliminated redundant error handling for random number generation as errors from these functions do not require special attention. This reduces code complexity and improves readability.
2024-09-20 20:39:50 +02:00
f5d4cdafea
Increase test iterations for SetMessageID randomness check
Updated the TestMsg_SetMessageIDRandomness test to run 50,000 iterations instead of 100, ensuring a more robust evaluation of the Msg.SetMessageID method's randomness. Additionally, streamlined the retrieval of Message ID using GetMessageID.
2024-09-20 20:39:30 +02:00
19330fc108
Refactor random number generation and add version-specific implementations
Removed error handling from `randNum` in `random_test.go` and introduced new `randNum` implementations for different Go versions (1.19, 1.20-1.21, 1.22+). This ensures compatibility with different versions of Go and utilizes the appropriate version-specific random number generation methods. We are using math/rand instead crypto/rand. For our needs this should be sufficient.
2024-09-20 20:30:23 +02:00
af9915e4e7
Add test for WriteToTempFile failure scenario
This new test verifies error handling for WriteToTempFile when the TMPDIR environment variable is set to an invalid directory. It ensures that the method fails as expected under these conditions, improving code robustness.
2024-09-20 19:45:49 +02:00
6f869e4efd
Merge pull request #302 from wneessen/feature/improve-client-tests
Improved client error testing
2024-09-20 17:51:19 +02:00
44df830348
Add tests for SendError MessageID and Msg methods
Introduce two new tests in senderror_test.go: TestSendError_MessageID and TestSendError_Msg. These tests validate the behavior of the MessageID and Msg methods of the SendError type, ensuring correct handling of message ID and sender information.
2024-09-20 17:00:08 +02:00
4ee11e8406
Refactor SMTP server port handling in tests
Modified tests to dynamically compute server ports from a base value, enhancing flexibility and preventing potential conflicts. Updated `simpleSMTPServer` function to accept a port parameter.
2024-09-20 16:44:15 +02:00
bd5a8a40b9
Fix error handling in Send method in client_119.go
Refine Send method to correctly typecast and accumulate SendError instances. Introduce "errors" package import to utilize errors.As for precise error type checking, ensuring accurate error lists. This regression was introduced with PR #301
2024-09-20 16:40:12 +02:00
8dfb121aec
Update Go versions in GitHub Actions workflow
Removed Go 1.21 and added Go 1.19 in the codecov.yml file to ensure compatibility with older projects and streamline the CI process. This helps in maintaining backward compatibility and avoids potential issues with unsupported Go versions.
2024-09-20 16:24:59 +02:00
d5437f6b7a
Remove redundant comments from sleep statements
Removed unnecessary comments that were clarifying the purpose of sleep statements in the test cases. This makes the code cleaner and easier to maintain by reducing clutter.
2024-09-20 16:23:31 +02:00
157c138142
Fix linter errors
Replaced `err == io.EOF` with `errors.Is(err, io.EOF)` for better error comparison. Removed redundant `break` statements to streamline case logic and improve code readability.
2024-09-20 15:58:51 +02:00
482194b4b3
Add TestClient_SendErrorReset to validate SMTP error handling
This test checks the client's ability to handle SMTP reset errors when sending an email. It verifies the correct error type, ensures it is recognized as a permanent error, and confirms the correct message ID handling.
2024-09-20 15:52:05 +02:00
b8f0462ce3
Add error handling tests for SMTP client
Implemented multiple tests to cover various error scenarios in the SMTP client, including invalid email addresses and data transmission failures. Introduced `failReset` flag in `simpleSMTPServer` to simulate server reset failures.
2024-09-20 15:49:03 +02:00
6af6a28f78
Add test for SendError with no encoding
Introduced `TestClient_SendErrorNoEncoding` to verify client behavior when sending a message without encoding. Adjusted server connection handling for better error reporting and connection closure, replacing abrupt exits with returns where appropriate.
2024-09-20 15:05:43 +02:00
0aa24c6f3a
Add methods to retrieve message ID and message from SendError
Implement MessageID and Msg methods in SendError to allow retrieval of the message ID and the affected message, respectively. These methods handle cases where the error or the message is nil, returning an empty string or nil as appropriate.
2024-09-20 15:05:26 +02:00
fbebcf96d8
Add simple SMTP test server for unit testing
Implemented a simple SMTP test server to facilitate unit testing. This server listens on a specified address and port, accepts connections, and processes common SMTP commands like HELO, MAIL FROM, RCPT TO, DATA, and QUIT. Several constants related to the server configuration were also added to the test file.
2024-09-20 14:48:24 +02:00
619318ba0d
Merge pull request #301 from wneessen/feature/168_improve-error-handling
Improved error handling
2024-09-20 11:02:49 +02:00
d400379e2f
Refactor error handling for SendError struct
Reformat the construction of SendError objects for better readability. This improves the clarity and maintainability of the error handling code within the client.go file.
2024-09-20 10:31:19 +02:00
fcbd202595
Add test for IsTemp method on nil SendError
This commit introduces a new test case to verify the behavior of the IsTemp method when called on a nil SendError instance. It ensures that the method returns false as expected, improving test coverage for edge cases.
2024-09-20 10:30:30 +02:00
db2ec99cd6
Merge pull request #300 from wneessen/dependabot/github_actions/github/codeql-action-3.26.8
Bump github/codeql-action from 3.26.7 to 3.26.8
2024-09-19 15:45:49 +02:00
dependabot[bot]
664b7299e6
Bump github/codeql-action from 3.26.7 to 3.26.8
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.26.7 to 3.26.8.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](8214744c54...294a9d9291)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-19 13:44:59 +00:00
508a2f2a6c
Refactor connection handling in tests
Replaced `getTestConnection` with `getTestConnectionNoTestPort` for tests that skip port configuration, improving connection setup flexibility. Added environment variable support for setting ports in `getTestClient` to streamline port configuration in tests.
2024-09-19 15:21:17 +02:00
f469ba977d
Add affected message ID to error log
Include the affected message ID in the error message to provide more context for debugging. This change ensures that each error log contains essential information about the specific message associated with the error.
2024-09-19 12:12:48 +02:00
0239318d94
Add affectedMsg field to SendError struct
Included the affected message in the SendError struct for better error tracking and debugging. This enhancement ensures that any errors encountered during the sending process can be directly associated with the specific message that caused them.
2024-09-19 12:09:23 +02:00
69e211682c
Add GetMessageID method to Msg
Introduced GetMessageID to retrieve the Message ID from the Msg
2024-09-19 11:46:53 +02:00
3bdb6f7cca
Refactor variable naming in Send method
Renamed variable `cerr` to `err` for consistency. This improves readability and standardizes error variable naming within the method.
2024-09-19 10:59:22 +02:00
277ae9be19
Refactor message sending logic
Consolidated the message sending logic into a single `sendSingleMsg` function to reduce duplication and improve code maintainability. This change simplifies the `Send` method in multiple Go version files by removing redundant code and calling the new helper function instead.
2024-09-19 10:56:01 +02:00
2e7156182a
Rename variable 'failed' to 'hasError' for clarity
Renamed the variable 'failed' to 'hasError' to better reflect its purpose and improve code readability. This change helps in understanding that the variable indicates the presence of an error rather than a generic failure.
2024-09-19 10:35:32 +02:00
8ee37abca2
Refactor error handling in message sending loop
Changed from range over messages to range with index to correctly update sendError field in the original messages slice. This prevents shadowing issues and ensures proper error logging for each message.
2024-09-18 12:29:42 +02:00
ee726487f1
Refactor message sending logic for better modularity
Extracted message sending functionality into a new helper function `sendSingleMsg`. This improves the code readability and maintainability by reducing the complexity of the main loop and encapsulating error handling per message.
2024-09-18 11:06:48 +02:00
1dd73778d4
Merge branch 'main' into feature/168_improve-error-handling 2024-09-18 10:33:06 +02:00
d3bea90761
Merge pull request #299 from wneessen/dependabot/github_actions/github/codeql-action-3.26.7
Bump github/codeql-action from 3.26.6 to 3.26.7
2024-09-16 15:51:08 +02:00
dependabot[bot]
68109ed40d
Bump github/codeql-action from 3.26.6 to 3.26.7
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.26.6 to 3.26.7.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](4dd16135b6...8214744c54)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-16 13:46:00 +00:00
94d5f3f7a1
Merge pull request #297 from wneessen/dependabot/github_actions/step-security/harden-runner-2.10.1
Bump step-security/harden-runner from 2.9.1 to 2.10.1
2024-09-11 16:14:56 +02:00
dependabot[bot]
6d9829776a
Bump step-security/harden-runner from 2.9.1 to 2.10.1
Bumps [step-security/harden-runner](https://github.com/step-security/harden-runner) from 2.9.1 to 2.10.1.
- [Release notes](https://github.com/step-security/harden-runner/releases)
- [Commits](5c7944e73c...91182cccc0)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-11 14:09:18 +00:00
a747f5f74c
Merge branch 'main' into feature/168_improve-error-handling 2024-09-06 11:15:50 +02:00
0ea9631855
Refactor error handling in message delivery process
The error handling process in sending messages has been refactored for better accuracy and efficiency. Instead of immediately joining errors and returning, they are now collected in a slice and joined in a deferred function to ensure all errors are captured before being returned. Furthermore, the SendError structure has been updated to include a reference to the affected message, providing better context for each error.
2024-07-16 13:07:20 +02:00
25 changed files with 1438 additions and 337 deletions

View file

@ -36,10 +36,10 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
go: ['1.20', '1.21', '1.22', '1.23']
go: ['1.19', '1.20', '1.23']
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
egress-policy: audit

View file

@ -45,7 +45,7 @@ jobs:
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
egress-policy: audit
@ -54,7 +54,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@4dd16135b69a43b6c8efb853346f8437d92d3c93 # v3.26.6
uses: github/codeql-action/init@e2b3eafc8d227b0241d48be5f425d47c2d750a13 # v3.26.10
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@ -65,7 +65,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@4dd16135b69a43b6c8efb853346f8437d92d3c93 # v3.26.6
uses: github/codeql-action/autobuild@e2b3eafc8d227b0241d48be5f425d47c2d750a13 # v3.26.10
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@ -79,4 +79,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@4dd16135b69a43b6c8efb853346f8437d92d3c93 # v3.26.6
uses: github/codeql-action/analyze@e2b3eafc8d227b0241d48be5f425d47c2d750a13 # v3.26.10

View file

@ -21,7 +21,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
egress-policy: audit

View file

@ -20,7 +20,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
egress-policy: audit

View file

@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
egress-policy: audit
- name: Run govulncheck

View file

@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
egress-policy: audit

View file

@ -35,7 +35,7 @@ jobs:
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
egress-policy: audit
@ -75,6 +75,6 @@ jobs:
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@4dd16135b69a43b6c8efb853346f8437d92d3c93 # v3.26.6
uses: github/codeql-action/upload-sarif@e2b3eafc8d227b0241d48be5f425d47c2d750a13 # v3.26.10
with:
sarif_file: results.sarif

View file

@ -27,7 +27,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
egress-policy: audit
@ -44,7 +44,7 @@ jobs:
run: |
go test -v -race --coverprofile=./cov.out ./...
- uses: sonarsource/sonarqube-scan-action@0c0f3958d90fc466625f1d1af1f47bddd4cc6bd1 # master
- uses: sonarsource/sonarqube-scan-action@884b79409bbd464b2a59edc326a4b77dc56b2195 # master
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}

166
client.go
View file

@ -12,6 +12,7 @@ import (
"net"
"os"
"strings"
"sync"
"time"
"github.com/wneessen/go-mail/log"
@ -87,12 +88,12 @@ type DialContextFunc func(ctx context.Context, network, address string) (net.Con
// Client is the SMTP client struct
type Client struct {
// connection is the net.Conn that the smtp.Client is based on
connection net.Conn
// Timeout for the SMTP server connection
connTimeout time.Duration
// dialContextFunc is a custom DialContext function to dial target SMTP server
dialContextFunc DialContextFunc
// dsn indicates that we want to use DSN for the Client
dsn bool
@ -102,11 +103,9 @@ type Client struct {
// dsnrntype defines the DSNRcptNotifyOption in case DSN is enabled
dsnrntype []string
// isEncrypted indicates if a Client connection is encrypted or not
isEncrypted bool
// noNoop indicates the Noop is to be skipped
noNoop bool
// fallbackPort is used as an alternative port number in case the primary port is unavailable or
// fails to bind.
fallbackPort int
// HELO/EHLO string for the greeting the target SMTP server
helo string
@ -114,12 +113,24 @@ type Client struct {
// Hostname of the target SMTP server to connect to
host string
// isEncrypted indicates if a Client connection is encrypted or not
isEncrypted bool
// logger is a logger that implements the log.Logger interface
logger log.Logger
// mutex is used to synchronize access to shared resources, ensuring that only one goroutine can
// modify them at a time.
mutex sync.RWMutex
// noNoop indicates the Noop is to be skipped
noNoop bool
// pass is the corresponding SMTP AUTH password
pass string
// Port of the SMTP server to connect to
port int
fallbackPort int
// port specifies the network port number on which the server listens for incoming connections.
port int
// smtpAuth is a pointer to smtp.Auth
smtpAuth smtp.Auth
@ -130,26 +141,20 @@ type Client struct {
// smtpClient is the smtp.Client that is set up when using the Dial*() methods
smtpClient *smtp.Client
// Use SSL for the connection
useSSL bool
// tlspolicy sets the client to use the provided TLSPolicy for the STARTTLS protocol
tlspolicy TLSPolicy
// tlsconfig represents the tls.Config setting for the STARTTLS connection
tlsconfig *tls.Config
// user is the SMTP AUTH username
user string
// useDebugLog enables the debug logging on the SMTP client
useDebugLog bool
// logger is a logger that implements the log.Logger interface
logger log.Logger
// user is the SMTP AUTH username
user string
// dialContextFunc is a custom DialContext function to dial target SMTP server
dialContextFunc DialContextFunc
// Use SSL for the connection
useSSL bool
}
// Option returns a function that can be used for grouping Client options
@ -550,6 +555,9 @@ func (c *Client) SetLogger(logger log.Logger) {
// SetTLSConfig overrides the current *tls.Config with the given *tls.Config value
func (c *Client) SetTLSConfig(tlsconfig *tls.Config) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if tlsconfig == nil {
return ErrInvalidTLSConfig
}
@ -589,6 +597,9 @@ func (c *Client) setDefaultHelo() error {
// DialWithContext establishes a connection to the SMTP server with a given context.Context
func (c *Client) DialWithContext(dialCtx context.Context) error {
c.mutex.Lock()
defer c.mutex.Unlock()
ctx, cancel := context.WithDeadline(dialCtx, time.Now().Add(c.connTimeout))
defer cancel()
@ -602,17 +613,16 @@ func (c *Client) DialWithContext(dialCtx context.Context) error {
c.dialContextFunc = tlsDialer.DialContext
}
}
var err error
c.connection, err = c.dialContextFunc(ctx, "tcp", c.ServerAddr())
connection, err := c.dialContextFunc(ctx, "tcp", c.ServerAddr())
if err != nil && c.fallbackPort != 0 {
// TODO: should we somehow log or append the previous error?
c.connection, err = c.dialContextFunc(ctx, "tcp", c.serverFallbackAddr())
connection, err = c.dialContextFunc(ctx, "tcp", c.serverFallbackAddr())
}
if err != nil {
return err
}
client, err := smtp.NewClient(c.connection, c.host)
client, err := smtp.NewClient(connection, c.host)
if err != nil {
return err
}
@ -691,7 +701,7 @@ func (c *Client) DialAndSendWithContext(ctx context.Context, messages ...*Msg) e
// checkConn makes sure that a required server connection is available and extends the
// connection deadline
func (c *Client) checkConn() error {
if c.connection == nil {
if !c.smtpClient.HasConnection() {
return ErrNoActiveConnection
}
@ -701,7 +711,7 @@ func (c *Client) checkConn() error {
}
}
if err := c.connection.SetDeadline(time.Now().Add(c.connTimeout)); err != nil {
if err := c.smtpClient.UpdateDeadline(c.connTimeout); err != nil {
return ErrDeadlineExtendFailed
}
return nil
@ -715,7 +725,7 @@ func (c *Client) serverFallbackAddr() string {
// tls tries to make sure that the STARTTLS requirements are satisfied
func (c *Client) tls() error {
if c.connection == nil {
if !c.smtpClient.HasConnection() {
return ErrNoActiveConnection
}
if !c.useSSL && c.tlspolicy != NoTLS {
@ -787,3 +797,103 @@ func (c *Client) auth() error {
}
return nil
}
// sendSingleMsg sends out a single message and returns an error if the transmission/delivery fails.
// It is invoked by the public Send methods
func (c *Client) sendSingleMsg(message *Msg) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if message.encoding == NoEncoding {
if ok, _ := c.smtpClient.Extension("8BITMIME"); !ok {
return &SendError{Reason: ErrNoUnencoded, isTemp: false, affectedMsg: message}
}
}
from, err := message.GetSender(false)
if err != nil {
return &SendError{
Reason: ErrGetSender, errlist: []error{err}, isTemp: isTempError(err),
affectedMsg: message,
}
}
rcpts, err := message.GetRecipients()
if err != nil {
return &SendError{
Reason: ErrGetRcpts, errlist: []error{err}, isTemp: isTempError(err),
affectedMsg: message,
}
}
if c.dsn {
if c.dsnmrtype != "" {
c.smtpClient.SetDSNMailReturnOption(string(c.dsnmrtype))
}
}
if err = c.smtpClient.Mail(from); err != nil {
retError := &SendError{
Reason: ErrSMTPMailFrom, errlist: []error{err}, isTemp: isTempError(err),
affectedMsg: message,
}
if resetSendErr := c.smtpClient.Reset(); resetSendErr != nil {
retError.errlist = append(retError.errlist, resetSendErr)
}
return retError
}
hasError := false
rcptSendErr := &SendError{affectedMsg: message}
rcptSendErr.errlist = make([]error, 0)
rcptSendErr.rcpt = make([]string, 0)
rcptNotifyOpt := strings.Join(c.dsnrntype, ",")
c.smtpClient.SetDSNRcptNotifyOption(rcptNotifyOpt)
for _, rcpt := range rcpts {
if err = c.smtpClient.Rcpt(rcpt); err != nil {
rcptSendErr.Reason = ErrSMTPRcptTo
rcptSendErr.errlist = append(rcptSendErr.errlist, err)
rcptSendErr.rcpt = append(rcptSendErr.rcpt, rcpt)
rcptSendErr.isTemp = isTempError(err)
hasError = true
}
}
if hasError {
if resetSendErr := c.smtpClient.Reset(); resetSendErr != nil {
rcptSendErr.errlist = append(rcptSendErr.errlist, resetSendErr)
}
return rcptSendErr
}
writer, err := c.smtpClient.Data()
if err != nil {
return &SendError{
Reason: ErrSMTPData, errlist: []error{err}, isTemp: isTempError(err),
affectedMsg: message,
}
}
_, err = message.WriteTo(writer)
if err != nil {
return &SendError{
Reason: ErrWriteContent, errlist: []error{err}, isTemp: isTempError(err),
affectedMsg: message,
}
}
message.isDelivered = true
if err = writer.Close(); err != nil {
return &SendError{
Reason: ErrSMTPDataClose, errlist: []error{err}, isTemp: isTempError(err),
affectedMsg: message,
}
}
if err = c.Reset(); err != nil {
return &SendError{
Reason: ErrSMTPReset, errlist: []error{err}, isTemp: isTempError(err),
affectedMsg: message,
}
}
if err = c.checkConn(); err != nil {
return &SendError{
Reason: ErrConnCheck, errlist: []error{err}, isTemp: isTempError(err),
affectedMsg: message,
}
}
return nil
}

View file

@ -7,111 +7,23 @@
package mail
import "strings"
import "errors"
// Send sends out the mail message
func (c *Client) Send(messages ...*Msg) error {
if cerr := c.checkConn(); cerr != nil {
return &SendError{Reason: ErrConnCheck, errlist: []error{cerr}, isTemp: isTempError(cerr)}
if err := c.checkConn(); err != nil {
return &SendError{Reason: ErrConnCheck, errlist: []error{err}, isTemp: isTempError(err)}
}
var errs []*SendError
for _, message := range messages {
message.sendError = nil
if message.encoding == NoEncoding {
if ok, _ := c.smtpClient.Extension("8BITMIME"); !ok {
sendErr := &SendError{Reason: ErrNoUnencoded, isTemp: false}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
}
from, err := message.GetSender(false)
if err != nil {
sendErr := &SendError{Reason: ErrGetSender, errlist: []error{err}, isTemp: isTempError(err)}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
rcpts, err := message.GetRecipients()
if err != nil {
sendErr := &SendError{Reason: ErrGetRcpts, errlist: []error{err}, isTemp: isTempError(err)}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
for id, message := range messages {
if sendErr := c.sendSingleMsg(message); sendErr != nil {
messages[id].sendError = sendErr
if c.dsn {
if c.dsnmrtype != "" {
c.smtpClient.SetDSNMailReturnOption(string(c.dsnmrtype))
var msgSendErr *SendError
if errors.As(sendErr, &msgSendErr) {
errs = append(errs, msgSendErr)
}
}
if err = c.smtpClient.Mail(from); err != nil {
sendErr := &SendError{Reason: ErrSMTPMailFrom, errlist: []error{err}, isTemp: isTempError(err)}
if resetSendErr := c.smtpClient.Reset(); resetSendErr != nil {
sendErr.errlist = append(sendErr.errlist, resetSendErr)
}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
failed := false
rcptSendErr := &SendError{}
rcptSendErr.errlist = make([]error, 0)
rcptSendErr.rcpt = make([]string, 0)
rcptNotifyOpt := strings.Join(c.dsnrntype, ",")
c.smtpClient.SetDSNRcptNotifyOption(rcptNotifyOpt)
for _, rcpt := range rcpts {
if err = c.smtpClient.Rcpt(rcpt); err != nil {
rcptSendErr.Reason = ErrSMTPRcptTo
rcptSendErr.errlist = append(rcptSendErr.errlist, err)
rcptSendErr.rcpt = append(rcptSendErr.rcpt, rcpt)
rcptSendErr.isTemp = isTempError(err)
failed = true
}
}
if failed {
if resetSendErr := c.smtpClient.Reset(); resetSendErr != nil {
rcptSendErr.errlist = append(rcptSendErr.errlist, err)
}
message.sendError = rcptSendErr
errs = append(errs, rcptSendErr)
continue
}
writer, err := c.smtpClient.Data()
if err != nil {
sendErr := &SendError{Reason: ErrSMTPData, errlist: []error{err}, isTemp: isTempError(err)}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
_, err = message.WriteTo(writer)
if err != nil {
sendErr := &SendError{Reason: ErrWriteContent, errlist: []error{err}, isTemp: isTempError(err)}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
message.isDelivered = true
if err = writer.Close(); err != nil {
sendErr := &SendError{Reason: ErrSMTPDataClose, errlist: []error{err}, isTemp: isTempError(err)}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
if err = c.Reset(); err != nil {
sendErr := &SendError{Reason: ErrSMTPReset, errlist: []error{err}, isTemp: isTempError(err)}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
if err = c.checkConn(); err != nil {
sendErr := &SendError{Reason: ErrConnCheck, errlist: []error{err}, isTemp: isTempError(err)}
message.sendError = sendErr
errs = append(errs, sendErr)
continue
}
}
if len(errs) > 0 {

View file

@ -9,7 +9,6 @@ package mail
import (
"errors"
"strings"
)
// Send sends out the mail message
@ -18,92 +17,16 @@ func (c *Client) Send(messages ...*Msg) (returnErr error) {
returnErr = &SendError{Reason: ErrConnCheck, errlist: []error{err}, isTemp: isTempError(err)}
return
}
for _, message := range messages {
message.sendError = nil
if message.encoding == NoEncoding {
if ok, _ := c.smtpClient.Extension("8BITMIME"); !ok {
message.sendError = &SendError{Reason: ErrNoUnencoded, isTemp: false}
returnErr = errors.Join(returnErr, message.sendError)
continue
}
}
from, err := message.GetSender(false)
if err != nil {
message.sendError = &SendError{Reason: ErrGetSender, errlist: []error{err}, isTemp: isTempError(err)}
returnErr = errors.Join(returnErr, message.sendError)
continue
}
rcpts, err := message.GetRecipients()
if err != nil {
message.sendError = &SendError{Reason: ErrGetRcpts, errlist: []error{err}, isTemp: isTempError(err)}
returnErr = errors.Join(returnErr, message.sendError)
continue
}
if c.dsn {
if c.dsnmrtype != "" {
c.smtpClient.SetDSNMailReturnOption(string(c.dsnmrtype))
}
}
if err = c.smtpClient.Mail(from); err != nil {
message.sendError = &SendError{Reason: ErrSMTPMailFrom, errlist: []error{err}, isTemp: isTempError(err)}
returnErr = errors.Join(returnErr, message.sendError)
if resetSendErr := c.smtpClient.Reset(); resetSendErr != nil {
returnErr = errors.Join(returnErr, resetSendErr)
}
continue
}
failed := false
rcptSendErr := &SendError{}
rcptSendErr.errlist = make([]error, 0)
rcptSendErr.rcpt = make([]string, 0)
rcptNotifyOpt := strings.Join(c.dsnrntype, ",")
c.smtpClient.SetDSNRcptNotifyOption(rcptNotifyOpt)
for _, rcpt := range rcpts {
if err = c.smtpClient.Rcpt(rcpt); err != nil {
rcptSendErr.Reason = ErrSMTPRcptTo
rcptSendErr.errlist = append(rcptSendErr.errlist, err)
rcptSendErr.rcpt = append(rcptSendErr.rcpt, rcpt)
rcptSendErr.isTemp = isTempError(err)
failed = true
}
}
if failed {
if resetSendErr := c.smtpClient.Reset(); resetSendErr != nil {
returnErr = errors.Join(returnErr, resetSendErr)
}
message.sendError = rcptSendErr
returnErr = errors.Join(returnErr, message.sendError)
continue
}
writer, err := c.smtpClient.Data()
if err != nil {
message.sendError = &SendError{Reason: ErrSMTPData, errlist: []error{err}, isTemp: isTempError(err)}
returnErr = errors.Join(returnErr, message.sendError)
continue
}
_, err = message.WriteTo(writer)
if err != nil {
message.sendError = &SendError{Reason: ErrWriteContent, errlist: []error{err}, isTemp: isTempError(err)}
returnErr = errors.Join(returnErr, message.sendError)
continue
}
message.isDelivered = true
var errs []error
defer func() {
returnErr = errors.Join(errs...)
}()
if err = writer.Close(); err != nil {
message.sendError = &SendError{Reason: ErrSMTPDataClose, errlist: []error{err}, isTemp: isTempError(err)}
returnErr = errors.Join(returnErr, message.sendError)
continue
}
if err = c.Reset(); err != nil {
message.sendError = &SendError{Reason: ErrSMTPReset, errlist: []error{err}, isTemp: isTempError(err)}
returnErr = errors.Join(returnErr, message.sendError)
continue
}
if err = c.checkConn(); err != nil {
message.sendError = &SendError{Reason: ErrConnCheck, errlist: []error{err}, isTemp: isTempError(err)}
returnErr = errors.Join(returnErr, message.sendError)
for id, message := range messages {
if sendErr := c.sendSingleMsg(message); sendErr != nil {
messages[id].sendError = sendErr
errs = append(errs, sendErr)
}
}

File diff suppressed because it is too large Load diff

15
msg.go
View file

@ -481,8 +481,8 @@ func (m *Msg) SetMessageID() {
if err != nil {
hostname = "localhost.localdomain"
}
randNumPrimary, _ := randNum(100000000)
randNumSecondary, _ := randNum(10000)
randNumPrimary := randNum(100000000)
randNumSecondary := randNum(10000)
randString, _ := randomStringSecure(17)
procID := os.Getpid() * randNumSecondary
messageID := fmt.Sprintf("%d.%d%d.%s@%s", procID, randNumPrimary, randNumSecondary,
@ -490,6 +490,17 @@ func (m *Msg) SetMessageID() {
m.SetMessageIDWithValue(messageID)
}
// GetMessageID returns the message ID of the Msg as string value. If no message ID
// is set, an empty string will be returned
func (m *Msg) GetMessageID() string {
if msgidheader, ok := m.genHeader[HeaderMessageID]; ok {
if len(msgidheader) > 0 {
return msgidheader[0]
}
}
return ""
}
// SetMessageIDWithValue sets the message id for the mail
func (m *Msg) SetMessageIDWithValue(messageID string) {
m.SetGenHeader(HeaderMessageID, fmt.Sprintf("<%s>", messageID))

View file

@ -61,3 +61,25 @@ func TestMsg_WriteToSendmail(t *testing.T) {
t.Errorf("WriteToSendmail failed: %s", err)
}
}
func TestMsg_WriteToTempFileFailed(t *testing.T) {
m := NewMsg()
_ = m.From("Toni Tester <tester@example.com>")
_ = m.To("Ellenor Tester <ellinor@example.com>")
m.SetBodyString(TypeTextPlain, "This is a test")
curTmpDir := os.Getenv("TMPDIR")
defer func() {
if err := os.Setenv("TMPDIR", curTmpDir); err != nil {
t.Errorf("failed to set TMPDIR environment variable: %s", err)
}
}()
if err := os.Setenv("TMPDIR", "/invalid/directory/that/does/not/exist"); err != nil {
t.Errorf("failed to set TMPDIR environment variable: %s", err)
}
_, err := m.WriteToTempFile()
if err == nil {
t.Errorf("WriteToTempFile() did not fail as expected")
}
}

View file

@ -786,13 +786,11 @@ func TestMsg_SetMessageIDWithValue(t *testing.T) {
// TestMsg_SetMessageIDRandomness tests the randomness of Msg.SetMessageID methods
func TestMsg_SetMessageIDRandomness(t *testing.T) {
var mids []string
for i := 0; i < 100; i++ {
for i := 0; i < 50_000; i++ {
m := NewMsg()
m.SetMessageID()
mid := m.GetGenHeader(HeaderMessageID)
if len(mid) > 0 {
mids = append(mids, mid[0])
}
mid := m.GetMessageID()
mids = append(mids, mid)
}
c := make(map[string]int)
for i := range mids {
@ -805,6 +803,21 @@ func TestMsg_SetMessageIDRandomness(t *testing.T) {
}
}
func TestMsg_GetMessageID(t *testing.T) {
expected := "this.is.a.message.id"
msg := NewMsg()
msg.SetMessageIDWithValue(expected)
val := msg.GetMessageID()
if !strings.EqualFold(val, fmt.Sprintf("<%s>", expected)) {
t.Errorf("GetMessageID() failed. Expected: %s, got: %s", fmt.Sprintf("<%s>", expected), val)
}
msg.genHeader[HeaderMessageID] = nil
val = msg.GetMessageID()
if val != "" {
t.Errorf("GetMessageID() failed. Expected empty string, got: %s", val)
}
}
// TestMsg_FromFormat tests the FromFormat and EnvelopeFrom methods for the Msg object
func TestMsg_FromFormat(t *testing.T) {
tests := []struct {

View file

@ -7,8 +7,6 @@ package mail
import (
"crypto/rand"
"encoding/binary"
"fmt"
"math/big"
"strings"
)
@ -52,23 +50,3 @@ func randomStringSecure(length int) (string, error) {
return randString.String(), nil
}
// randNum returns a random number with a maximum value of length
func randNum(length int) (int, error) {
if length <= 0 {
return 0, fmt.Errorf("provided number is <= 0: %d", length)
}
length64 := big.NewInt(int64(length))
if !length64.IsUint64() {
return 0, fmt.Errorf("big.NewInt() generation returned negative value: %d", length64)
}
randNum64, err := rand.Int(rand.Reader, length64)
if err != nil {
return 0, err
}
randomNum := int(randNum64.Int64())
if randomNum < 0 {
return 0, fmt.Errorf("generated random number does not fit as int64: %d", randNum64)
}
return randomNum, nil
}

22
random_119.go Normal file
View file

@ -0,0 +1,22 @@
// SPDX-FileCopyrightText: 2022-2023 The go-mail Authors
//
// SPDX-License-Identifier: MIT
//go:build !go1.20
// +build !go1.20
package mail
import (
"math/rand"
"time"
)
// randNum returns a random number with a maximum value of length
func randNum(maxval int) int {
if maxval <= 0 {
return 0
}
rand.Seed(time.Now().UnixNano())
return rand.Intn(maxval)
}

20
random_121.go Normal file
View file

@ -0,0 +1,20 @@
// SPDX-FileCopyrightText: 2022-2023 The go-mail Authors
//
// SPDX-License-Identifier: MIT
//go:build go1.20 && !go1.22
// +build go1.20,!go1.22
package mail
import (
"math/rand"
)
// randNum returns a random number with a maximum value of length
func randNum(maxval int) int {
if maxval <= 0 {
return 0
}
return rand.Intn(maxval)
}

22
random_122.go Normal file
View file

@ -0,0 +1,22 @@
// SPDX-FileCopyrightText: 2022-2023 The go-mail Authors
//
// SPDX-License-Identifier: MIT
//go:build go1.22
// +build go1.22
package mail
import (
"math/rand/v2"
)
// randNum returns a random number with a maximum value of maxval.
// go-mail compiled with Go 1.22+ will make use of the novel math/rand/v2 interface
// Older versions of Go will use math/rand
func randNum(maxval int) int {
if maxval <= 0 {
return 0
}
return rand.IntN(maxval)
}

View file

@ -55,16 +55,17 @@ func TestRandomNum(t *testing.T) {
for _, tc := range tt {
t.Run(tc.testName, func(t *testing.T) {
rn, err := randNum(tc.max)
if err != nil {
t.Errorf("random number generation failed: %s", err)
}
if rn < 0 {
t.Errorf("random number generation failed: %d is smaller than zero", rn)
}
rn := randNum(tc.max)
if rn > tc.max {
t.Errorf("random number generation failed: %d is bigger than given value %d", rn, tc.max)
}
})
}
}
func TestRandomNumZero(t *testing.T) {
rn := randNum(0)
if rn != 0 {
t.Errorf("random number generation failed: %d is not zero", rn)
}
}

View file

@ -56,10 +56,11 @@ const (
// SendError is an error wrapper for delivery errors of the Msg
type SendError struct {
Reason SendErrReason
isTemp bool
errlist []error
rcpt []string
affectedMsg *Msg
errlist []error
isTemp bool
rcpt []string
Reason SendErrReason
}
// SendErrReason represents a comparable reason on why the delivery failed
@ -92,6 +93,11 @@ func (e *SendError) Error() string {
}
}
}
if e.affectedMsg != nil && e.affectedMsg.GetMessageID() != "" {
errMessage.WriteString(", affected message ID: ")
errMessage.WriteString(e.affectedMsg.GetMessageID())
}
return errMessage.String()
}
@ -112,6 +118,23 @@ func (e *SendError) IsTemp() bool {
return e.isTemp
}
// MessageID returns the message ID of the affected Msg that caused the error
// If no message ID was set for the Msg, an empty string will be returned
func (e *SendError) MessageID() string {
if e == nil || e.affectedMsg == nil {
return ""
}
return e.affectedMsg.GetMessageID()
}
// Msg returns the pointer to the affected message that caused the error
func (e *SendError) Msg() *Msg {
if e == nil || e.affectedMsg == nil {
return nil
}
return e.affectedMsg
}
// String implements the Stringer interface for the SendErrReason
func (r SendErrReason) String() string {
switch r {

View file

@ -83,7 +83,96 @@ func TestSendError_IsTemp(t *testing.T) {
}
}
func TestSendError_IsTempNil(t *testing.T) {
var se *SendError
if se.IsTemp() {
t.Error("expected false on nil-senderror")
}
}
func TestSendError_MessageID(t *testing.T) {
var se *SendError
err := returnSendError(ErrAmbiguous, false)
if !errors.As(err, &se) {
t.Errorf("error mismatch, expected error to be of type *SendError")
return
}
if errors.As(err, &se) {
if se.MessageID() == "" {
t.Errorf("sendError expected message-id, but got empty string")
}
if !strings.EqualFold(se.MessageID(), "<this.is.a.message.id>") {
t.Errorf("sendError message-id expected: %s, but got: %s", "<this.is.a.message.id>",
se.MessageID())
}
}
}
func TestSendError_MessageIDNil(t *testing.T) {
var se *SendError
if se.MessageID() != "" {
t.Error("expected empty string on nil-senderror")
}
}
func TestSendError_Msg(t *testing.T) {
var se *SendError
err := returnSendError(ErrAmbiguous, false)
if !errors.As(err, &se) {
t.Errorf("error mismatch, expected error to be of type *SendError")
return
}
if errors.As(err, &se) {
if se.Msg() == nil {
t.Errorf("sendError expected msg pointer, but got nil")
}
from := se.Msg().GetFromString()
if len(from) == 0 {
t.Errorf("sendError expected msg from, but got empty string")
return
}
if !strings.EqualFold(from[0], "<toni.tester@domain.tld>") {
t.Errorf("sendError message from expected: %s, but got: %s", "<toni.tester@domain.tld>",
from[0])
}
}
}
func TestSendError_MsgNil(t *testing.T) {
var se *SendError
if se.Msg() != nil {
t.Error("expected nil on nil-senderror")
}
}
func TestSendError_IsFail(t *testing.T) {
err1 := returnSendError(ErrAmbiguous, false)
err2 := returnSendError(ErrSMTPMailFrom, false)
if errors.Is(err1, err2) {
t.Errorf("error mismatch, ErrAmbiguous should not be equal to ErrSMTPMailFrom")
}
}
func TestSendError_ErrorMulti(t *testing.T) {
expected := `ambiguous reason, check Msg.SendError for message specific reasons, ` +
`affected recipient(s): <email1@domain.tld>, <email2@domain.tld>`
err := &SendError{
Reason: ErrAmbiguous, isTemp: false, affectedMsg: nil,
rcpt: []string{"<email1@domain.tld>", "<email2@domain.tld>"},
}
if err.Error() != expected {
t.Errorf("error mismatch, expected: %s, got: %s", expected, err.Error())
}
}
// returnSendError is a helper method to retunr a SendError with a specific reason
func returnSendError(r SendErrReason, t bool) error {
return &SendError{Reason: r, isTemp: t}
message := NewMsg()
_ = message.From("toni.tester@domain.tld")
_ = message.To("tina.tester@domain.tld")
message.Subject("This is the subject")
message.SetBodyString(TypeTextPlain, "This is the message body")
message.SetMessageIDWithValue("this.is.a.message.id")
return &SendError{Reason: r, isTemp: t, affectedMsg: message}
}

View file

@ -30,34 +30,57 @@ import (
"net/textproto"
"os"
"strings"
"sync"
"time"
"github.com/wneessen/go-mail/log"
)
// A Client represents a client connection to an SMTP server.
type Client struct {
// Text is the textproto.Conn used by the Client. It is exported to allow for
// clients to add extensions.
// Text is the textproto.Conn used by the Client. It is exported to allow for clients to add extensions.
Text *textproto.Conn
// keep a reference to the connection so it can be used to create a TLS
// connection later
// auth supported auth mechanisms
auth []string
// keep a reference to the connection so it can be used to create a TLS connection later
conn net.Conn
// whether the Client is using TLS
tls bool
serverName string
// map of supported extensions
// debug logging is enabled
debug bool
// didHello indicates whether we've said HELO/EHLO
didHello bool
// dsnmrtype defines the mail return option in case DSN is enabled
dsnmrtype string
// dsnrntype defines the recipient notify option in case DSN is enabled
dsnrntype string
// ext is a map of supported extensions
ext map[string]string
// supported auth mechanisms
auth []string
localName string // the name to use in HELO/EHLO
didHello bool // whether we've said HELO/EHLO
helloError error // the error from the hello
// debug logging
debug bool // debug logging is enabled
logger log.Logger // logger will be used for debug logging
// DSN support
dsnmrtype string // dsnmrtype defines the mail return option in case DSN is enabled
dsnrntype string // dsnrntype defines the recipient notify option in case DSN is enabled
// helloError is the error from the hello
helloError error
// localName is the name to use in HELO/EHLO
localName string // the name to use in HELO/EHLO
// logger will be used for debug logging
logger log.Logger
// mutex is used to synchronize access to shared resources, ensuring that only one goroutine can access
// the resource at a time.
mutex sync.RWMutex
// tls indicates whether the Client is using TLS
tls bool
// serverName denotes the name of the server to which the application will connect. Used for
// identification and routing.
serverName string
}
// Dial returns a new [Client] connected to an SMTP server at addr.
@ -94,7 +117,10 @@ func NewClient(conn net.Conn, host string) (*Client, error) {
// Close closes the connection.
func (c *Client) Close() error {
return c.Text.Close()
c.mutex.Lock()
err := c.Text.Close()
c.mutex.Unlock()
return err
}
// hello runs a hello exchange if needed.
@ -121,28 +147,39 @@ func (c *Client) Hello(localName string) error {
if c.didHello {
return errors.New("smtp: Hello called after other methods")
}
c.mutex.Lock()
c.localName = localName
c.mutex.Unlock()
return c.hello()
}
// cmd is a convenience function that sends a command and returns the response
func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, error) {
c.mutex.Lock()
c.debugLog(log.DirClientToServer, format, args...)
id, err := c.Text.Cmd(format, args...)
if err != nil {
c.mutex.Unlock()
return 0, "", err
}
c.Text.StartResponse(id)
defer c.Text.EndResponse(id)
code, msg, err := c.Text.ReadResponse(expectCode)
c.debugLog(log.DirServerToClient, "%d %s", code, msg)
c.Text.EndResponse(id)
c.mutex.Unlock()
return code, msg, err
}
// helo sends the HELO greeting to the server. It should be used only when the
// server does not support ehlo.
func (c *Client) helo() error {
c.mutex.Lock()
c.ext = nil
c.mutex.Unlock()
_, _, err := c.cmd(250, "HELO %s", c.localName)
return err
}
@ -157,9 +194,13 @@ func (c *Client) StartTLS(config *tls.Config) error {
if err != nil {
return err
}
c.mutex.Lock()
c.conn = tls.Client(c.conn, config)
c.Text = textproto.NewConn(c.conn)
c.tls = true
c.mutex.Unlock()
return c.ehlo()
}
@ -167,11 +208,15 @@ func (c *Client) StartTLS(config *tls.Config) error {
// The return values are their zero values if [Client.StartTLS] did
// not succeed.
func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool) {
c.mutex.RLock()
defer c.mutex.RUnlock()
tc, ok := c.conn.(*tls.Conn)
if !ok {
return
}
return tc.ConnectionState(), true
state, ok = tc.ConnectionState(), true
return
}
// Verify checks the validity of an email address on the server.
@ -257,6 +302,8 @@ func (c *Client) Mail(from string) error {
return err
}
cmdStr := "MAIL FROM:<%s>"
c.mutex.RLock()
if c.ext != nil {
if _, ok := c.ext["8BITMIME"]; ok {
cmdStr += " BODY=8BITMIME"
@ -269,6 +316,8 @@ func (c *Client) Mail(from string) error {
cmdStr += fmt.Sprintf(" RET=%s", c.dsnmrtype)
}
}
c.mutex.RUnlock()
_, _, err := c.cmd(250, cmdStr, from)
return err
}
@ -280,7 +329,11 @@ func (c *Client) Rcpt(to string) error {
if err := validateLine(to); err != nil {
return err
}
c.mutex.RLock()
_, ok := c.ext["DSN"]
c.mutex.RUnlock()
if ok && c.dsnrntype != "" {
_, _, err := c.cmd(25, "RCPT TO:<%s> NOTIFY=%s", to, c.dsnrntype)
return err
@ -294,12 +347,23 @@ type dataCloser struct {
io.WriteCloser
}
// Close releases the lock, closes the WriteCloser, waits for a response, and then returns any error encountered.
func (d *dataCloser) Close() error {
d.c.mutex.Lock()
_ = d.WriteCloser.Close()
_, _, err := d.c.Text.ReadResponse(250)
d.c.mutex.Unlock()
return err
}
// Write writes data to the underlying WriteCloser while ensuring thread-safety by locking and unlocking a mutex.
func (d *dataCloser) Write(p []byte) (n int, err error) {
d.c.mutex.Lock()
n, err = d.WriteCloser.Write(p)
d.c.mutex.Unlock()
return
}
// Data issues a DATA command to the server and returns a writer that
// can be used to write the mail headers and body. The caller should
// close the writer before calling any more methods on c. A call to
@ -309,7 +373,14 @@ func (c *Client) Data() (io.WriteCloser, error) {
if err != nil {
return nil, err
}
return &dataCloser{c, c.Text.DotWriter()}, nil
datacloser := &dataCloser{}
c.mutex.Lock()
datacloser.c = c
datacloser.WriteCloser = c.Text.DotWriter()
c.mutex.Unlock()
return datacloser, nil
}
var testHookStartTLS func(*tls.Config) // nil, except for tests
@ -405,7 +476,10 @@ func (c *Client) Extension(ext string) (bool, string) {
return false, ""
}
ext = strings.ToUpper(ext)
c.mutex.RLock()
param, ok := c.ext[ext]
c.mutex.RUnlock()
return ok, param
}
@ -438,7 +512,11 @@ func (c *Client) Quit() error {
if err != nil {
return err
}
return c.Text.Close()
c.mutex.Lock()
err = c.Text.Close()
c.mutex.Unlock()
return err
}
// SetDebugLog enables the debug logging for incoming and outgoing SMTP messages
@ -472,6 +550,21 @@ func (c *Client) SetDSNRcptNotifyOption(d string) {
c.dsnrntype = d
}
// HasConnection checks if the client has an active connection.
// Returns true if the `conn` field is not nil, indicating an active connection.
func (c *Client) HasConnection() bool {
return c.conn != nil
}
func (c *Client) UpdateDeadline(timeout time.Duration) error {
c.mutex.Lock()
if err := c.conn.SetDeadline(time.Now().Add(timeout)); err != nil {
return fmt.Errorf("smtp: failed to update deadline: %w", err)
}
c.mutex.Unlock()
return nil
}
// debugLog checks if the debug flag is set and if so logs the provided message to
// the log.Logger interface
func (c *Client) debugLog(d log.Direction, f string, a ...interface{}) {

View file

@ -25,6 +25,9 @@ func (c *Client) ehlo() error {
if err != nil {
return err
}
c.mutex.Lock()
defer c.mutex.Unlock()
ext := make(map[string]string)
extList := strings.Split(msg, "\n")
if len(extList) > 1 {

View file

@ -22,12 +22,15 @@ import "strings"
// should be the preferred greeting for servers that support it.
//
// Backport of: https://github.com/golang/go/commit/4d8db00641cc9ff4f44de7df9b8c4f4a4f9416ee#diff-4f6f6bdb9891d4dd271f9f31430420a2e44018fe4ee539576faf458bebb3cee4
// to guarantee backwards compatibility with Go 1.16/1.17:w
// to guarantee backwards compatibility with Go 1.16/1.17
func (c *Client) ehlo() error {
_, msg, err := c.cmd(250, "EHLO %s", c.localName)
if err != nil {
return err
}
c.mutex.Lock()
defer c.mutex.Unlock()
ext := make(map[string]string)
extList := strings.Split(msg, "\n")
if len(extList) > 1 {