From 491b5941aae02c580853bdf048e8bb5fff95dc69 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Thu, 9 Jun 2022 09:57:01 +0200 Subject: [PATCH] #18: Added `WriteToTempfile()` which will create a temporary output file - We have two versions of this method: - One for Go versions below 1.17 using `ioutil.TempFile()` - One for Go versions >= 1.17 using `os.CreateTemp()` --- msg_totmpfile.go | 20 ++++++++++++++++++++ msg_totmpfile_116.go | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 msg_totmpfile.go create mode 100644 msg_totmpfile_116.go diff --git a/msg_totmpfile.go b/msg_totmpfile.go new file mode 100644 index 00000000..a2f33bb7 --- /dev/null +++ b/msg_totmpfile.go @@ -0,0 +1,20 @@ +//go:build go1.17 +// +build go1.17 + +package mail + +import ( + "fmt" + "os" +) + +// WriteToTempfile will create a temporary file and output the Msg to this file +// The method will return the filename of the temporary file +func (m *Msg) WriteToTempfile() (string, error) { + f, err := os.CreateTemp("", "go-mail_*.eml") + if err != nil { + return "", fmt.Errorf("failed to create output file: %w", err) + } + defer func() { _ = f.Close() }() + return f.Name(), m.WriteToFile(f.Name()) +} diff --git a/msg_totmpfile_116.go b/msg_totmpfile_116.go new file mode 100644 index 00000000..e1857a0e --- /dev/null +++ b/msg_totmpfile_116.go @@ -0,0 +1,20 @@ +//go:build !go1.17 +// +build !go1.17 + +package mail + +import ( + "fmt" + "io/ioutil" +) + +// WriteToTempfile will create a temporary file and output the Msg to this file +// The method will return the filename of the temporary file +func (m *Msg) WriteToTempfile() (string, error) { + f, err := ioutil.TempFile("", "go-mail_*.eml") + if err != nil { + return "", fmt.Errorf("failed to create output file: %w", err) + } + defer func() { _ = f.Close() }() + return f.Name(), m.WriteToFile(f.Name()) +}