golang golang发送邮件网/ smtp SMTP

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang golang发送邮件网/ smtp SMTP相关的知识,希望对你有一定的参考价值。

package main

import (

  "log"
	"net/mail"
	"encoding/base64"
	"net/smtp"
	"fmt"
	"strings"
)

func encodeRFC2047(String string) string{
	// use mail's rfc2047 to encode any string
	addr := mail.Address{String, ""}
	return strings.Trim(addr.String(), " <>")
}


func main() {
	// Set up authentication information.

	smtpServer := "smtp.163.com"
	auth := smtp.PlainAuth(
		"",
		"fledna@163.com",
		"password*******",
		smtpServer,
	)

	from := mail.Address{"监控中心", "fledna@163.com"}
	to := mail.Address{"收件人", "name@139.com"}
	title := "当前时段统计报表"

	body := "报表内容一切正常";

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = encodeRFC2047(title)
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; charset=\"utf-8\""
	header["Content-Transfer-Encoding"] = "base64"

	message := ""
	for k, v := range header {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(body))

	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		smtpServer + ":25",
		auth,
		from.Address,
		[]string{to.Address},
		[]byte(message),
		//[]byte("This is the email body."),
	)
	if err != nil {
		log.Fatal(err)
	}
}

golang 使用Go(Golang)通过GMail发送电子邮件与net / smtp

package main

import (
	"log"
	"net/smtp"
)

func main() {
	send("hello there")
}

func send(body string) {
	from := "...@gmail.com"
	pass := "..."
	to := "foobarbazz@mailinator.com"

	msg := "From: " + from + "\n" +
		"To: " + to + "\n" +
		"Subject: Hello there\n\n" +
		body

	err := smtp.SendMail("smtp.gmail.com:587",
		smtp.PlainAuth("", from, pass, "smtp.gmail.com"),
		from, []string{to}, []byte(msg))

	if err != nil {
		log.Printf("smtp error: %s", err)
		return
	}
	
	log.Print("sent, visit http://foobarbazz.mailinator.com")
}

以上是关于golang golang发送邮件网/ smtp SMTP的主要内容,如果未能解决你的问题,请参考以下文章

在 Golang 中附加文件并通过 SMTP 发送时没有正文部分的电子邮件

GoLang邮件发送Demo(继上篇msmtp)

Golang发送邮件

Golang发送邮件

golang 使用 gomail 发送邮件

通过 smtp 发送电子邮件并更改发件人姓名