github.com/zhigang2008/qrserver@v0.0.0-20150521135340-51313e45d270/dqs/util/mailer.go (about)

     1  package util
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  	log "github.com/cihub/seelog"
     7  	"github.com/jpoehls/gophermail"
     8  	"net/smtp"
     9  )
    10  
    11  var (
    12  	b64 = base64.StdEncoding
    13  )
    14  
    15  type Mailer struct {
    16  	Host     string
    17  	Port     string
    18  	auth     smtp.Auth
    19  	Mail     string
    20  	User     string
    21  	Password string
    22  }
    23  
    24  //初始化mailer
    25  func InitMailer(host, port, mail string, auth bool, user, password string) *Mailer {
    26  	mailer := Mailer{
    27  		Host:     host,
    28  		Port:     port,
    29  		Mail:     mail,
    30  		User:     user,
    31  		Password: password}
    32  
    33  	if auth {
    34  		mailer.auth = smtp.PlainAuth(
    35  			"",
    36  			mailer.User,
    37  			mailer.Password,
    38  			mailer.Host)
    39  	} else {
    40  		mailer.auth = smtp.PlainAuth(
    41  			"",
    42  			"",
    43  			"",
    44  			mailer.Host)
    45  	}
    46  	return &mailer
    47  }
    48  
    49  //发送邮件
    50  func (m *Mailer) SendMail(to []string, subject, body string) error {
    51  
    52  	header := make(map[string]string)
    53  	header["From"] = m.Mail
    54  	header["MIME-Version"] = "1.0"
    55  	header["Content-Type"] = "text/html; charset=UTF-8"
    56  	header["Content-Transfer-Encoding"] = "base64"
    57  	toaddr := ""
    58  	for _, v := range to {
    59  		toaddr += v + ";"
    60  	}
    61  	header["To"] = toaddr
    62  	header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(subject)))
    63  
    64  	message := ""
    65  	for k, v := range header {
    66  		message += fmt.Sprintf("%s: %s\r\n", k, v)
    67  	}
    68  	message += "\r\n" + b64.EncodeToString([]byte(body))
    69  
    70  	err := smtp.SendMail(
    71  		m.Host+":"+m.Port,
    72  		m.auth,
    73  		m.Mail,
    74  		to,
    75  		[]byte(message),
    76  	)
    77  	if err != nil {
    78  		log.Errorf("发送失败:%s", err.Error())
    79  		return err
    80  
    81  	}
    82  	return nil
    83  }
    84  
    85  //发送邮件
    86  func SendMulityMail(host, port string, auth bool, user, password string, msg *gophermail.Message) error {
    87  	addr := fmt.Sprintf("%s:%s", host, port)
    88  	var mailAuth smtp.Auth
    89  	if auth {
    90  		mailAuth = smtp.PlainAuth(
    91  			"",
    92  			user,
    93  			password,
    94  			host)
    95  	} else {
    96  		mailAuth = smtp.PlainAuth(
    97  			"",
    98  			"",
    99  			"",
   100  			host)
   101  	}
   102  	return gophermail.SendMail(addr, mailAuth, msg)
   103  }