使用官方gomail包+163邮箱发送邮件

使用golang官方标准包gomail发送邮件

pkg/mail/mail.go 文件

// 结构基本上是安装教程来走的
package mail

import (
    "github.com/sreio/gohub/pkg/config"
    "sync"
)

type Form struct {
    Address string
    Name    string
}

type Files struct {
    FileName string
    FilePath string
}

type Email struct {
    Form
    To       []string
    Cc       []string
    Subject  string
    HtmlBody string // Html message (optional)
    File     []Files
}

type Mailer struct {
    SMTPDriver Driver
}

var once sync.Once
var internalMailer *Mailer

func NewMailer() *Mailer {
    once.Do(func() {
        internalMailer = &Mailer{
            SMTPDriver: &SMTP{},
        }
    })
    return internalMailer
}

func (m *Mailer) SmtpSend(email Email) bool {
    return m.SMTPDriver.Send(email, config.GetStringMapString("mail.smtp"))
}

pkg/mail/mail_interface.go 文件

//这里的接口方法定义和教程一致
package mail

type Driver interface {
    Send(email Email, config map[string]string) bool
}

pkg/mail/driver_smtp.go 文件

//官方实例很简单
package mail

import (
    "github.com/spf13/cast"
    "github.com/sreio/gohub/pkg/logger"
    "gopkg.in/gomail.v2"
)

type SMTP struct{}

// Send 实现Driver方法
func (s *SMTP) Send(email Email, config map[string]string) bool {
    m := gomail.NewMessage()

    // 发送者
    m.SetHeader("From", m.FormatAddress(email.Form.Address, email.Form.Name))

    // 接收者
    m.SetHeader("To", email.To...)
    //m.SetAddressHeader("To", "dan@example.com", "Dan")

    // 抄送者
    m.SetHeader("Cc", email.Cc...)
    //m.SetAddressHeader("Cc", "dan@example.com", "Dan")

    // 邮件标题
    m.SetHeader("Subject", email.Subject)

    // 邮件正文
    m.SetBody("text/html", email.HtmlBody)

    // 邮件附件
    if len(email.File) > 0 {
        //m.Attach("/home/Alex/lolcat.jpg")
        for _, files := range email.File {
            m.Attach(files.FilePath, gomail.Rename(files.FileName))
        }
    }

    logger.DebugJSON("发送邮件", "发件详情", email)

    d := gomail.NewDialer(config["host"], cast.ToInt(config["port"]), config["username"], config["password"])

    // Send the email to Bob, Cora and Dan.
    if err := d.DialAndSend(m); err != nil {
        logger.ErrorString("发送邮件", "发件出错", err.Error())
        return false
    }

    logger.DebugString("发送邮件", "发件成功", "")
    return true
}

pkg/verifycode/verifycode.go

// SendMail 发送邮件验证码
func (c VerifyCode) SendMail(email string) error {
    code := c.generateVerifyCode(email)

// 这里我只想在本地环境
    if app.IsLocal() && strings.HasSuffix(email, config.Get("verifycode.debug_email_suffix")) {
        return nil
    }

    content := `
        <h1>您的 Email 验证码是 <strong>%v</strong> </h1>        
`
    content = fmt.Sprintf(content, code)

    mail.NewMailer().SmtpSend(mail.Email{
        Form: mail.Form{
            Address: config.Get("mail.form.address"),
            Name:    config.Get("mail.form.name"),
        },
        To:       []string{email},
        Subject:  "Email 验证码",
        HtmlBody: content,
    })

    return nil
}

config/mail.go

package config

import "github.com/sreio/gohub/pkg/config"

func init() {
    config.Add("mail", func() map[string]interface{} {
        return map[string]interface{}{
            "smtp": map[string]interface{}{
                "host":     config.Env("MAIL_SMTP_HOST", "localhost"),
                "port":     config.Env("MAIL_SMTP_PORT", 1025),
                "username": config.Env("MAIL_SMTP_USERNAME", ""),
                "password": config.Env("MAIL_MAIL_PASSWORD", ""),
            },
            "form": map[string]interface{}{
                "address": config.Env("MAIL_FROM_ADDRESS", "123456@163.com"),
                "name":    config.Env("MAIL_FROM_NAME", "weidada"),
            },
        }
    })
}

.env

MAIL_SMTP_HOST=smtp.163.com
MAIL_SMTP_PORT=465
MAIL_SMTP_USERNAME=123456@163.com
MAIL_MAIL_PASSWORD=授权码
MAIL_FROM_ADDRESS=123456@163.com
MAIL_FROM_NAME=发送人名称

感觉官方的标准包使用也是很方便的,也没有用到 Mailhog ,感觉多此一举,现在注册个人邮箱跟方便的,所以不如实战发送邮件

sreio
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!