package main
import (
"encoding/json"
"github.com/Unknwon/goconfig"
"gopkg.in/gomail.v2"
"log"
"net/http"
"net/url"
"regexp"
)
// 一些必须的配置
type Config struct {
User string
Password string
Host string
Port int
ServerAddr string
}
// 返回的response对象
type Response struct {
Success bool `json:"success"`
Msg string `json:"msg"`
ErrMsg string `json:"err_msg"`
}
func NewResponse(success bool, msg string, errMsg string) *Response {
return &Response{Success: success, Msg: msg, ErrMsg: errMsg}
}
// 处理发送邮件的表单
type EmailForm struct {
ToEmail string
Subject string
Body string
}
func NewEmailForm(toEmail string, subject string, body string) *EmailForm {
return &EmailForm{ToEmail: toEmail, Subject: subject, Body: body}
}
// 发送邮件
func sendMail(toMail, subject, body string) error {
mail := gomail.NewMessage()
mail.SetHeader("From", e.User)
mail.SetHeader("To", []string{toMail}...)
mail.SetHeader("Subject", subject)
mail.SetBody("text/html", body)
return gomail.NewDialer(e.Host, e.Port, e.User, e.Password).DialAndSend(mail)
}
// 邮件发送的表单校验
func ValidateEmailForm(emailForm url.Values) (*EmailForm, bool) {
toEmail := emailForm.Get("to_email")
subject := emailForm.Get("subject")
body := emailForm.Get("body")
pattern := `w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*`
reg := regexp.MustCompile(pattern)
var ok bool
if ok = reg.Match([]byte(toEmail)); ok == true {
return NewEmailForm(toEmail, subject, body), ok
}
return nil, ok
}
// 发邮件的handler
func HandleEmail(writer http.ResponseWriter, request *http.Request) {
response := NewResponse(false, "", "服务器开小差了")
if request.Method == "POST" {
writer.Header().Set("content-type", "application/json; charset=utf-8")
if err := request.ParseForm(); err == nil {
// todo 参数校验
var emailForm *EmailForm
var ok bool
if emailForm, ok = ValidateEmailForm(request.Form); ok == false {
response = NewResponse(false, "", "邮箱格式不正确")
goto Reply
}
// 这里可以选择开一个协程来发邮件速度会更快
//go sendMail(emailForm.ToEmail, emailForm.Subject, emailForm.Body)
if err := sendMail(emailForm.ToEmail, emailForm.Subject, emailForm.Body); err == nil {
response = NewResponse(true, "发送成功!", "")
goto Reply
}
}
goto Reply
Reply:
result, _ := json.Marshal(response)
writer.Write(result)
} else {
writer.WriteHeader(405)
writer.Write([]byte("Method Not Allowed"))
}
}
var e *Config
// 读配置文件初始化参数
func loadConfigFromFile(filePath string) {
cfg, err := goconfig.LoadConfigFile(filePath)
if err != nil {
log.Fatal(err)
}
if e.Host, err = cfg.GetValue("email", "host"); err != nil {
log.Fatal(err)
}
if e.Port, err = cfg.Int("email", "port"); err != nil {
log.Fatal(err)
}
if e.Password, err = cfg.GetValue("email", "password"); err != nil {
log.Fatal(err)
}
if e.User, err = cfg.GetValue("email", "user"); err != nil {
log.Fatal(err)
}
e.ServerAddr = cfg.MustValue("server", "address", ":8009")
}
// 全局初始化函数
func init() {
e = new(Config)
loadConfigFromFile("config.ini")
}
func main() {
http.HandleFunc("/email/", HandleEmail)
err := http.ListenAndServe(e.ServerAddr, nil)
if err != nil {
log.Fatal(err)
}
}
最后配置文件格式
[email]
host = smtp.qq.com
port = 25
user =
password =
[server]
address = :8009