diff --git a/bang.go b/bang.go index 1813275..c6bebcf 100644 --- a/bang.go +++ b/bang.go @@ -6,8 +6,8 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "io" + "io/ioutil" "log" "net/http" "os" @@ -93,6 +93,23 @@ func saveEmail(email Email) error { return json.NewEncoder(f).Encode(email) } +// Save a copy to the sender's mailbox (not in a subfolder) +func saveSentCopy(email Email) error { + mu.Lock() + defer mu.Unlock() + senderDir := filepath.Join(mailboxDir, email.From) + if err := os.MkdirAll(senderDir, 0755); err != nil { + return err + } + filePath := filepath.Join(senderDir, email.ID+".json") + f, err := os.Create(filePath) + if err != nil { + return err + } + defer f.Close() + return json.NewEncoder(f).Encode(email) +} + func createUserHandler(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) @@ -159,13 +176,17 @@ func receiveEmailHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, "Invalid JSON", http.StatusBadRequest) return } + email.ID = fmt.Sprintf("%d", time.Now().UnixNano()) + email.Timestamp = time.Now() if email.Domain == "brandon.ad" { - email.ID = fmt.Sprintf("%d", time.Now().UnixNano()) - email.Timestamp = time.Now() if err := saveEmail(email); err != nil { http.Error(w, "Failed to save email", http.StatusInternalServerError) return } + // Save a copy to the sender's mailbox (not in a subfolder) + if err := saveSentCopy(email); err != nil { + log.Printf("Warning: failed to save sent copy: %v", err) + } w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(map[string]string{"status": "ok", "id": email.ID}) return @@ -183,6 +204,10 @@ func receiveEmailHandler(w http.ResponseWriter, r *http.Request) { return } defer resp.Body.Close() + // Save a copy to the sender's mailbox (not in a subfolder) + if err := saveSentCopy(email); err != nil { + log.Printf("Warning: failed to save sent copy: %v", err) + } w.WriteHeader(resp.StatusCode) io.Copy(w, resp.Body) }