GolangNote

Golang笔记

Golang 用标准库通过Gmail smtp 发送邮件

Permalink

Golang 提供net/smtp 标准库来通过smtp 发送邮件,下面是通过Gmail 的smtp 来发送邮件的代码实例。

Golang 用标准库通过Gmail smtp 发送邮件

Go: smtp.gmail
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main

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

type EmailConfig struct {
    Username string
    Password string
    Host     string
    Port     int
}

func main() {
    // authentication configuration
    smtpHost := "smtp.gmail.com"   // 你可以改为其他的
    smtpPort := 587                // 端口
    smtpPass := "yourpassword"        // 密码
    smtpUser := "youname@gmail.com" // 用户

    emailConf := &EmailConfig{smtpUser, smtpPass, smtpHost, smtpPort}

    emailauth := smtp.PlainAuth("", emailConf.Username, emailConf.Password, emailConf.Host)

    sender := "yourname@gmail.com" // 发送者

    receivers := []string{
        "tosb1@qq.com",  // 收件人1
        "tosb2@qq.com", // 收件人2
    } 

    message := []byte("To: recipient@example.net\r\n" +
        "Subject: discount Gophers!\r\n" +
        "\r\n" +
        "This is the email body. Hello from Go SMTP package.\r\n") // your message

    // send out the email
    err := smtp.SendMail(smtpHost+":"+strconv.Itoa(emailConf.Port), //convert port number from int to string
        emailauth,
        sender,
        receivers,
        message,
    )

    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("well done")
}

需要注意的是,gmail 的新安全策略需要设置“特殊密码”来发送。

官方库使用参考 net/smtp

本文网址: https://golangnote.com/topic/30.html 转摘请注明来源

Related articles

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Write a Comment to "Golang 用标准库通过Gmail smtp 发送邮件"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms