go 發送郵件

搜索出來的使用go 發用郵件的例子並不能成功發送,因此搜到了下面這個用來解決這個問題git

504 5.7.4 Unrecognized authentication typegithub

package services

import (
	"fmt"
	"net/smtp"
	"strings"
)

const (
	EmailTo = "xxxx@163.com"  //發送給誰
	EmailFrom = "xxxx@163.com"  //誰發的
	EmailPass = "xxxxxxx" //密碼
	EmailHost = "smtp.163.com"  //通常是25端口
	EmailPort = "25" //通常是25端口
)


type loginAuth struct {
	username, password string
}

func LoginAuth(username, password string) smtp.Auth {
	return &loginAuth{username, password}
}

//須要使用Login做爲參數
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
	return "LOGIN", nil, nil 
}

func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
	command := string(fromServer)
	command = strings.TrimSpace(command)
	command = strings.TrimSuffix(command, ":")
	command = strings.ToLower(command)

	if more {
		if command == "username" {
			return []byte(fmt.Sprintf("%s", a.username)), nil
		} else if command == "password" {
			return []byte(fmt.Sprintf("%s", a.password)), nil
		} else {
			// We've already sent everything.
			return nil, fmt.Errorf("unexpected server challenge: %s", command)
		}
	}
	return nil, nil
}

func SendEmail(subject, body string) error {
	send_to := strings.Split(EmailTo, ";")
	content_type := "Content-Type: text/plain; charset=UTF-8"
	msg := []byte("To: All \r\nFrom: " + EmailFrom + " >\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)

	auth := LoginAuth(EmailFrom, EmailPass)
	err := smtp.SendMail(EmailHost+":"+EmailPort, auth, EmailFrom, send_to, msg)
	return err
}

須要本身實現smtp.Auth接口 而後Start()方法中添加"Login"參數。code

注意:發送的郵箱必須是開啓了smtp的,否則會發送不成功。server

PS: 以爲不錯的請點個贊吧!! (ง •̀_•́)ง接口

相關文章
相關標籤/搜索