diff --git a/smtp/session.go b/smtp/session.go index a2c06ad..0449f44 100644 --- a/smtp/session.go +++ b/smtp/session.go @@ -74,16 +74,15 @@ func (s *session) Data(r io.Reader) error { files = append(files, attachments...) files = append(files, inlines...) - email := &utils.Email{ - MessageID: eml.GetHeader("Message-Id"), - InReplyTo: eml.GetHeader("In-Reply-To"), - Subject: eml.GetHeader("Subject"), - From: s.from, - To: s.to, - Text: eml.Text, - HTML: eml.HTML, - Files: files, - } + email := utils.NewEmail( + eml.GetHeader("Message-Id"), + eml.GetHeader("In-Reply-To"), + eml.GetHeader("Subject"), + s.from, + s.to, + eml.Text, + eml.HTML, + files) return s.client.Send(s.ctx, email) } diff --git a/utils/email.go b/utils/email.go index de3bfd9..5e3f24e 100644 --- a/utils/email.go +++ b/utils/email.go @@ -11,3 +11,27 @@ type Email struct { HTML string Files []*File } + +// NewEmail constructs Email object +func NewEmail(messageID, inReplyTo, subject, from, to, text, html string, files []*File) *Email { + email := &Email{ + MessageID: messageID, + InReplyTo: inReplyTo, + From: from, + To: to, + Subject: subject, + Text: text, + HTML: html, + Files: files, + } + + if html != "" { + var err error + html, err = StripHTMLTag(html, "style") + if err == nil { + email.HTML = html + } + } + + return email +} diff --git a/utils/html.go b/utils/html.go new file mode 100644 index 0000000..35e477b --- /dev/null +++ b/utils/html.go @@ -0,0 +1,44 @@ +package utils + +import ( + "bytes" + "strings" + + "golang.org/x/net/html" +) + +// StripHTMLTag from text +// +// Source: https://siongui.github.io/2018/01/16/go-remove-html-inline-style/ +func StripHTMLTag(text, tag string) (string, error) { + doc, err := html.Parse(strings.NewReader(text)) + if err != nil { + return "", err + } + stripHTMLTag(doc, tag) + + var out bytes.Buffer + err = html.Render(&out, doc) + if err != nil { + return "", err + } + + return out.String(), nil +} + +func stripHTMLTag(node *html.Node, tag string) { + i := -1 + for index, attr := range node.Attr { + if attr.Key == tag { + i = index + break + } + } + if i != -1 { + node.Attr = append(node.Attr[:i], node.Attr[i+1:]...) + } + + for child := node.FirstChild; child != nil; child = child.NextSibling { + stripHTMLTag(child, tag) + } +}