100 lines
1.6 KiB
Go
100 lines
1.6 KiB
Go
package mail
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"fmt"
|
|
"net/smtp"
|
|
|
|
"qmail/internal/config"
|
|
)
|
|
|
|
func SendMail(server *config.Server, from string, to []string, data []byte) error {
|
|
fmt.Println("Send...")
|
|
if server.Host == "" || server.Port == 0 {
|
|
return fmt.Errorf("invalide server host or port")
|
|
}
|
|
|
|
fmt.Printf("Dial:%s:%d\n", server.Host, server.Port)
|
|
// Connect to the remote SMTP server.
|
|
|
|
c, err := smtp.Dial(fmt.Sprintf("%s:%d", server.Host, server.Port))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Println("omg")
|
|
if server.UseTLS {
|
|
fmt.Println("start TLS")
|
|
err = c.StartTLS(&tls.Config{
|
|
InsecureSkipVerify: true,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if server.Auth != nil {
|
|
fmt.Println("Auth")
|
|
auth := smtp.PlainAuth("", server.Auth.Login, server.Auth.Password, server.Host)
|
|
err = c.Auth(auth)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if from == "" {
|
|
from = server.From
|
|
}
|
|
|
|
if from == "" {
|
|
return fmt.Errorf("From not set")
|
|
}
|
|
|
|
fmt.Printf("Set from: %s\n", from)
|
|
// Set the sender and recipient first
|
|
if err := c.Mail(from); err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(to) == 0 {
|
|
to = []string{server.To}
|
|
}
|
|
|
|
if len(to) == 0 {
|
|
return fmt.Errorf("To not set")
|
|
}
|
|
|
|
for _, tt := range to {
|
|
if err := c.Rcpt(tt); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
// Send the email body.
|
|
wc, err := c.Data()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("Send data")
|
|
_, err = wc.Write(data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = wc.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Println("Code connection")
|
|
// Send the QUIT command and close the connection.
|
|
err = c.Quit()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Println("Done")
|
|
return nil
|
|
}
|