golang-发送邮件

前端之家收集整理的这篇文章主要介绍了golang-发送邮件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
亲测可用
 
package main

import (
	m "chUtils/mail"
	"fmt"
)

func main() {
	email := m.NewEmail("305860361@qq.com","测试主题","测试了")
	err := m.SendEmail(email)
	if err != nil {
		fmt.Print(err)
	}
}
 
 
 
<pre name="code" class="csharp">package mail

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

const (
	HOST        = "smtp.163.com"
	SERVER_ADDR = "smtp.163.com:25"
	USER        = "a15207146487@163.com" //发送邮件的邮箱
	PASSWORD    = "iadblvahqephdpzl"     //发送邮件邮箱的密码
)

type Email struct {
	to      string "to"
	subject string "subject"
	msg     string "msg"
}

func NewEmail(to,subject,msg string) *Email {
	return &Email{to: to,subject: subject,msg: msg}
}

func SendEmail(email *Email) error {
	auth := smtp.PlainAuth("",USER,PASSWORD,HOST)
	sendTo := strings.Split(email.to,";")
	done := make(chan error,1024)

	go func() {
		defer close(done)
		for _,v := range sendTo {

			str := strings.Replace("From: "+USER+"~To: "+v+"~Subject: "+email.subject+"~~","~","\r\n",-1) + email.msg

			err := smtp.SendMail(
				SERVER_ADDR,auth,[]string{v},[]byte(str),)
			done <- err
		}
	}()

	for i := 0; i < len(sendTo); i++ {
		fmt.Println(<-done)
	}

	return nil
}
原文链接:https://www.f2er.com/go/190256.html

猜你在找的Go相关文章