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: 以为不错的请点个赞吧!! (ง •̀_•́)ง接口

相关文章
相关标签/搜索