-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
72 lines (58 loc) · 1.57 KB
/
Copy pathmain.go
File metadata and controls
72 lines (58 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"log"
"net/http"
"net/smtp"
"os"
)
type EmailRequest struct {
To string `json:"to" binding:"required"`
Subject string `json:"subject" binding:"required"`
Body string `json:"body" binding:"required"`
}
func sendEmail(to, subject, body string) error {
from := os.Getenv("EMAIL_ADDRESS")
password := os.Getenv("EMAIL_PASSWORD")
// SMTP server configuration.
smtpHost := os.Getenv("SMTP_HOST")
smtpPort := os.Getenv("SMTP_PORT")
// Message.
msg := []byte("From: " + from + "\n" +
"To: " + to + "\n" +
"Subject: " + subject + "\n\n" +
body)
// Authentication.
auth := smtp.PlainAuth("", from, password, smtpHost)
// Sending email.
err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, []string{to}, msg)
if err != nil {
return err
}
return nil
}
func main() {
// Load .env file
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file")
}
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.POST("/send-email", func(c *gin.Context) {
var emailRequest EmailRequest
if err := c.ShouldBindJSON(&emailRequest); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err := sendEmail(emailRequest.To, emailRequest.Subject, emailRequest.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to send email: " + err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Email sent successfully!"})
})
log.Println("Listening on port:" + os.Getenv("PORT"))
r.Run(":8081")
}