Skip to content

Commit

Permalink
Simplify Message-ID generation
Browse files Browse the repository at this point in the history
Updated the SetMessageID method to generate a "Message-ID" using a
single randomly generated string combined with the hostname, replacing
the prior complex format that included process ID and multiple random
numbers. This change simplifies the code of the generated IDs.
  • Loading branch information
wneessen committed Oct 7, 2024
1 parent 5c8b2fc commit 5874911
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 12 deletions.
18 changes: 7 additions & 11 deletions msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -972,12 +972,12 @@ func (m *Msg) Subject(subj string) {

// SetMessageID generates and sets a unique "Message-ID" header for the Msg.
//
// This method creates a "Message-ID" string using the current process ID, random numbers, and the hostname
// of the machine. The generated ID helps uniquely identify the message in email systems, facilitating tracking
// and preventing duplication. If the hostname cannot be retrieved, it defaults to "localhost.localdomain".
// This method creates a "Message-ID" string using a randomly generated string and the hostname of the machine.
// The generated ID helps uniquely identify the message in email systems, facilitating tracking and preventing
// duplication. If the hostname cannot be retrieved, it defaults to "localhost.localdomain".
//
// The generated Message-ID follows the format
// "<processID.randomNumberPrimary.randomNumberSecondary.randomString@hostname>".
// "<randomString@hostname>".
//
// References:
// - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.4
Expand All @@ -986,13 +986,9 @@ func (m *Msg) SetMessageID() {
if err != nil {
hostname = "localhost.localdomain"
}
randNumPrimary := randNum(100000000)
randNumSecondary := randNum(10000)
randString, _ := randomStringSecure(17)
procID := os.Getpid() * randNumSecondary
messageID := fmt.Sprintf("%d.%d%d.%s@%s", procID, randNumPrimary, randNumSecondary,
randString, hostname)
m.SetMessageIDWithValue(messageID)
// We have 64 possible characters, which for a 22 character string, provides approx. 132 bits of entropy.
randString, _ := randomStringSecure(22)
m.SetMessageIDWithValue(fmt.Sprintf("%s@%s", randString, hostname))
}

// GetMessageID retrieves the "Message-ID" header from the Msg.
Expand Down
2 changes: 1 addition & 1 deletion msg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -786,8 +786,8 @@ func TestMsg_SetMessageIDWithValue(t *testing.T) {
// TestMsg_SetMessageIDRandomness tests the randomness of Msg.SetMessageID methods
func TestMsg_SetMessageIDRandomness(t *testing.T) {
var mids []string
m := NewMsg()
for i := 0; i < 50_000; i++ {
m := NewMsg()
m.SetMessageID()
mid := m.GetMessageID()
mids = append(mids, mid)
Expand Down

0 comments on commit 5874911

Please sign in to comment.