@@ -22,6 +22,13 @@ type AdminAnnouncement struct {
2222 Body string `json:"announcement" binding:"required"`
2323}
2424
25+ // EmailUser struct for data needed when admin sends new email to a user
26+ type EmailUser struct {
27+ Subject string `json:"subject" binding:"required"`
28+ Body string `json:"body" binding:"required"`
29+ Email string `json:"email" binding:"required" validate:"mail"`
30+ }
31+
2532// UpdateMaintenanceInput struct for data needed when user update maintenance
2633type UpdateMaintenanceInput struct {
2734 ON bool `json:"on" binding:"required"`
@@ -419,6 +426,53 @@ func (a *App) CreateNewAnnouncement(req *http.Request) (interface{}, Response) {
419426 }, Created ()
420427}
421428
429+ // SendEmail creates a new administrator email and sends it to a specific user as an email and notification
430+ func (a * App ) SendEmail (req * http.Request ) (interface {}, Response ) {
431+ var emailUser EmailUser
432+ err := json .NewDecoder (req .Body ).Decode (& emailUser )
433+
434+ if err != nil {
435+ log .Error ().Err (err ).Send ()
436+ return nil , BadRequest (errors .New ("failed to read email data" ))
437+ }
438+
439+ err = validator .Validate (emailUser )
440+ if err != nil {
441+ log .Error ().Err (err ).Send ()
442+ return nil , BadRequest (errors .New ("invalid email data" ))
443+ }
444+
445+ user , err := a .db .GetUserByEmail (emailUser .Email )
446+ if err == gorm .ErrRecordNotFound {
447+ log .Error ().Err (err ).Send ()
448+ return nil , BadRequest (errors .New ("user is not found" ))
449+ }
450+
451+ if err != nil {
452+ log .Error ().Err (err ).Send ()
453+ return nil , BadRequest (errors .New ("failed to get user" ))
454+ }
455+
456+ subject , body := internal .AdminMailContent (emailUser .Subject , emailUser .Body , a .config .Server .Host , user .Name )
457+
458+ err = internal .SendMail (a .config .MailSender .Email , a .config .MailSender .SendGridKey , user .Email , subject , body )
459+ if err != nil {
460+ log .Error ().Err (err ).Send ()
461+ return nil , InternalServerError (errors .New (internalServerErrorMsg ))
462+ }
463+
464+ notification := models.Notification {UserID : user .ID .String (), Msg : fmt .Sprintf ("Email: %s" , emailUser .Body )}
465+ err = a .db .CreateNotification (& notification )
466+ if err != nil {
467+ log .Error ().Err (err ).Send ()
468+ return nil , InternalServerError (errors .New (internalServerErrorMsg ))
469+ }
470+
471+ return ResponseMsg {
472+ Message : "new email is sent successfully" ,
473+ }, Created ()
474+ }
475+
422476// UpdateNextLaunchHandler updates next launch flag
423477func (a * App ) UpdateNextLaunchHandler (req * http.Request ) (interface {}, Response ) {
424478 var input UpdateNextLaunchInput
0 commit comments