service/library/email/send.go

54 lines
1.3 KiB
Go
Raw Normal View History

2024-08-23 16:17:32 +08:00
package email
import (
"fmt"
2024-08-23 16:53:36 +08:00
"io"
"net/http"
2024-08-23 16:17:32 +08:00
"service/dbstruct"
"service/library/logger"
"strings"
"gopkg.in/gomail.v2"
)
2024-10-15 16:02:08 +08:00
func SendRavenIQTestResult(mail *dbstruct.Email, host string, port int, address, password string) error {
2024-08-23 16:17:32 +08:00
url := mail.MediaComponent.Images[0].Urls[0]
2024-08-23 17:04:31 +08:00
format := mail.MediaComponent.Images[0].Fmt
2024-08-23 16:17:32 +08:00
body := &strings.Builder{}
h2 := fmt.Sprintf("<h2>%v</h2>", mail.GetText())
img := fmt.Sprintf("<img border=\"0\" src=\"%v\" alt=\"图片加载错误,请联系管理员\">", url)
body.WriteString(h2)
body.WriteString(img)
2024-08-23 16:53:36 +08:00
response, err := http.Get(url)
if err != nil {
return err
}
attach, err := io.ReadAll(response.Body)
response.Body.Close()
if err != nil {
return err
}
2024-08-23 17:07:56 +08:00
attachName := fmt.Sprintf("测评结果.%v", format[6:])
2024-08-23 16:53:36 +08:00
2024-08-23 16:17:32 +08:00
m := gomail.NewMessage()
2024-10-15 16:54:43 +08:00
m.SetHeader("From", mail.GetFrom())
2024-08-23 16:17:32 +08:00
m.SetHeader("To", mail.GetTo())
m.SetHeader("Subject", mail.GetSubject())
m.SetBody("text/html", body.String())
2024-08-23 17:04:31 +08:00
m.Attach(attachName, gomail.SetCopyFunc(func(w io.Writer) error { //设置邮件附件 第一个参数是附件名称 第二个参数是二进制文件流
2024-08-23 16:53:36 +08:00
_, err := w.Write(attach)
return err
}))
2024-08-23 16:17:32 +08:00
2024-10-15 16:02:08 +08:00
err = gomail.NewDialer(host, port, address, password).DialAndSend(m)
2024-08-23 16:17:32 +08:00
if err != nil {
logger.Error("Send Email Fail", err)
return err
}
return nil
}