code.gitea.io/gitea@v1.19.3/modules/private/mail.go (about) 1 // Copyright 2020 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package private 5 6 import ( 7 "context" 8 "fmt" 9 "io" 10 "net/http" 11 12 "code.gitea.io/gitea/modules/json" 13 "code.gitea.io/gitea/modules/setting" 14 ) 15 16 // Email structure holds a data for sending general emails 17 type Email struct { 18 Subject string 19 Message string 20 To []string 21 } 22 23 // SendEmail calls the internal SendEmail function 24 // 25 // It accepts a list of usernames. 26 // If DB contains these users it will send the email to them. 27 // 28 // If to list == nil its supposed to send an email to every 29 // user present in DB 30 func SendEmail(ctx context.Context, subject, message string, to []string) (int, string) { 31 reqURL := setting.LocalURL + "api/internal/mail/send" 32 33 req := newInternalRequest(ctx, reqURL, "POST") 34 req = req.Header("Content-Type", "application/json") 35 jsonBytes, _ := json.Marshal(Email{ 36 Subject: subject, 37 Message: message, 38 To: to, 39 }) 40 req.Body(jsonBytes) 41 resp, err := req.Response() 42 if err != nil { 43 return http.StatusInternalServerError, fmt.Sprintf("Unable to contact gitea: %v", err.Error()) 44 } 45 defer resp.Body.Close() 46 47 body, err := io.ReadAll(resp.Body) 48 if err != nil { 49 return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error()) 50 } 51 52 users := fmt.Sprintf("%d", len(to)) 53 if len(to) == 0 { 54 users = "all" 55 } 56 57 return http.StatusOK, fmt.Sprintf("Sent %s email(s) to %s users", body, users) 58 }