一个发邮件的demo 用golang

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

一个发邮件的demo 用golang

文件目录树:

-d:\test\goemail
-| 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+"~~", "~", "\r\n", -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

本文来自:博客园

感谢作者:rojas

查看原文:一个发邮件的demo 用golang

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。