Rework FromAddress to prevent all the nesting

This commit is contained in:
Melon 2025-01-10 23:52:43 +00:00
parent 7aeeab415a
commit c322ffd8cb
Signed by: melon
GPG Key ID: 6C9D970C50D26A25
3 changed files with 16 additions and 9 deletions

View File

@ -5,17 +5,24 @@ import (
"github.com/emersion/go-message/mail" "github.com/emersion/go-message/mail"
) )
type FromAddress struct { type FromAddress mail.Address
*mail.Address
}
var _ encoding.TextUnmarshaler = &FromAddress{} var _ encoding.TextUnmarshaler = &FromAddress{}
func (f FromAddress) String() string {
return f.toMailAddress().String()
}
func (f *FromAddress) UnmarshalText(b []byte) error { func (f *FromAddress) UnmarshalText(b []byte) error {
address, err := mail.ParseAddress(string(b)) address, err := mail.ParseAddress(string(b))
if err != nil { if err != nil {
return err return err
} }
f.Address = address *f = FromAddress(*address)
return nil return nil
} }
func (f FromAddress) toMailAddress() *mail.Address {
m := mail.Address(f)
return &m
}

View File

@ -11,13 +11,13 @@ func TestFromAddress_UnmarshalText(t *testing.T) {
t.Run("json", func(t *testing.T) { t.Run("json", func(t *testing.T) {
var fromAddress FromAddress var fromAddress FromAddress
assert.NoError(t, json.Unmarshal([]byte(`"Jane Doe <jane@example.com>"`), &fromAddress)) assert.NoError(t, json.Unmarshal([]byte(`"Jane Doe <jane@example.com>"`), &fromAddress))
assert.Equal(t, "Jane Doe", fromAddress.Address.Name) assert.Equal(t, "Jane Doe", fromAddress.Name)
assert.Equal(t, "jane@example.com", fromAddress.Address.Address) assert.Equal(t, "jane@example.com", fromAddress.Address)
}) })
t.Run("yaml", func(t *testing.T) { t.Run("yaml", func(t *testing.T) {
var fromAddress FromAddress var fromAddress FromAddress
assert.NoError(t, yaml.Unmarshal([]byte(`"Jane Doe <jane@example.com>"`), &fromAddress)) assert.NoError(t, yaml.Unmarshal([]byte(`"Jane Doe <jane@example.com>"`), &fromAddress))
assert.Equal(t, "Jane Doe", fromAddress.Address.Name) assert.Equal(t, "Jane Doe", fromAddress.Name)
assert.Equal(t, "jane@example.com", fromAddress.Address.Address) assert.Equal(t, "jane@example.com", fromAddress.Address)
}) })
} }

View File

@ -77,7 +77,7 @@ func (m *Mail) SendMail(subject string, to []*mail.Address, htmlBody, textBody i
var h mail.Header var h mail.Header
h.SetDate(time.Now()) h.SetDate(time.Now())
h.SetSubject(subject) h.SetSubject(subject)
h.SetAddressList("From", []*mail.Address{m.From.Address}) h.SetAddressList("From", []*mail.Address{m.From.toMailAddress()})
h.SetAddressList("To", to) h.SetAddressList("To", to)
h.Set("Content-Type", "multipart/alternative") h.Set("Content-Type", "multipart/alternative")