zoukankan      html  css  js  c++  java
  • golang 创建发送邮件服务

    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
    
    
    
  • 相关阅读:
    WebFlux系列(二) Server-Sent Events
    WebFlux系列(一)HelloWorld
    Reactor系列(十九)StepVerifier测试
    C++中vector和set使用sort方法排序
    获取线程ID
    C标准中一些预定义的宏__DATE__ __FILE__ __LINE__ __TIME__ __func__
    opencv测试代码
    nohub相关
    tensorflow相关练习
    摄像机相关
  • 原文地址:https://www.cnblogs.com/ivy-blogs/p/13685405.html
Copyright © 2011-2022 走看看