github.com/greenpau/go-authcrunch@v1.1.4/pkg/messaging/file_send.go (about) 1 // Copyright 2022 Paul Greenberg greenpau@outlook.com 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package messaging 16 17 import ( 18 "github.com/greenpau/go-authcrunch/pkg/errors" 19 "github.com/greenpau/go-authcrunch/pkg/util" 20 "io/ioutil" 21 "os" 22 "path/filepath" 23 "strings" 24 "time" 25 ) 26 27 // FileProviderSendInput is input for FileProvider.Send function. 28 type FileProviderSendInput struct { 29 Subject string `json:"subject,omitempty" xml:"subject,omitempty" yaml:"subject,omitempty"` 30 Body string `json:"body,omitempty" xml:"body,omitempty" yaml:"body,omitempty"` 31 Recipients []string `json:"recipients,omitempty" xml:"recipients,omitempty" yaml:"recipients,omitempty"` 32 } 33 34 // Send writes a message to a file system. 35 func (p *FileProvider) Send(req *FileProviderSendInput) error { 36 fileInfo, err := os.Stat(p.RootDir) 37 if err != nil { 38 if !os.IsNotExist(err) { 39 return errors.ErrMessagingProviderDir.WithArgs(err) 40 } 41 if err := os.MkdirAll(p.RootDir, 0700); err != nil { 42 return errors.ErrMessagingProviderDir.WithArgs(err) 43 } 44 } 45 if fileInfo != nil && !fileInfo.IsDir() { 46 return errors.ErrMessagingProviderDir.WithArgs(p.RootDir + "is not a directory") 47 } 48 49 msgID := util.GetRandomString(64) 50 fp := filepath.Join(p.RootDir, msgID[:32]+".eml") 51 52 msg := "MIME-Version: 1.0\n" 53 msg += "Date: " + time.Now().Format(time.RFC1123Z) + "\n" 54 msg += "Subject: " + req.Subject + "\n" 55 msg += "Thread-Topic: Account Registration." + "\n" 56 msg += "Message-ID: <" + msgID + ">" + "\n" 57 msg += `To: ` + strings.Join(req.Recipients, ", ") + "\n" 58 59 msg += "Content-Transfer-Encoding: quoted-printable" + "\n" 60 msg += `Content-Type: text/html; charset="utf-8"` + "\n" 61 62 msg += "\r\n" + req.Body 63 64 if err := ioutil.WriteFile(fp, []byte(msg), 0600); err != nil { 65 return errors.ErrMessagingProviderSend.WithArgs(err) 66 } 67 return nil 68 }