一个发邮件的demo 用golang

   一个比较成熟的第三方包用来发邮件,可以带图片 和附件,项目地址 : github.com/go-gomail/gomail

一个发邮件的demo 用golang

文件目录树:

-d: estgoemail
-| libofm
       -| mymem.go
  |dosendmail.go

myem.go

package libofm

import (
    "net/smtp"
    "strings"
)

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

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+"~~", "~", "
", -1) + email.msg

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

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

    return nil
}

dosendmail.go

package main

import (
    "fmt"
    "test/goemail/libofm"
)

func main() {
    mycontent := " my dear令"

    email := libofm.NewEmail("xxxxx@qq.com;xxxxxx@qq.com;",
        "test golang email", mycontent)

    err := libofm.SendEmail(email)

    fmt.Println(err)

}

资源 http://files.cnblogs.com/files/rojas/goemail.zip

原文地址:https://www.cnblogs.com/rojas/p/4383291.html