前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go 发送邮件

go 发送邮件

作者头像
solate
发布2019-07-19 17:43:59
4030
发布2019-07-19 17:43:59
举报
文章被收录于专栏:solate 杂货铺solate 杂货铺

挑战A.I.,赢百万奖金......了解更多详情>>>

搜索出来的使用go 发用邮件的例子并不能成功发送,所以搜到了下面这个用来解决这个问题

504 5.7.4 Unrecognized authentication type

代码语言:javascript
复制
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"参数。

注意:发送的邮箱必须是开启了smtp的,不然会发送不成功。

PS: 觉得不错的请点个赞吧!! (ง •̀_•́)ง

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档