golang傳送郵件

2021-09-27 12:51:07 字數 2747 閱讀 6490

使用場景

使用模組

國內郵箱服務商位址

專案pop

smtp

阿里企業郵箱

pop3.mxhichina.com(:110/995)

smtp.mxhichina.com(:25/465)

pop.exmail.qq.com(:110/995)

smtp.exmail.qq.com(:25/465)

踩的坑

//準備郵件報文

email :=

"to: "

+ to +

"\n"

+"from: "

+ username +

"\n"

+"subject: "

+ subject +

"\n"

+"content-type: text/html; charset=utf-8"

+"\n"

+"content-transfer-encoding: base64"

+"\n\n"

+//坑在此 "\n\n"

base64.stdencoding.

encodetostring

(buf.

bytes()

)

解釋一哈: stmp 是一種郵件傳送協議,所有的協議都是有格式的,stmp也不例外。協議格式基本是由協議頭,空行,協議體組成。

協議頭空行(必須存在! \n\n 就是新增空行,否則郵件服務不能解析郵件體)

協議體**片段

//目錄結構

//100

// |--src/main/main.go

// |--src/test/mail.go

// |--template/active.html

//author: richard

package test

import

("bytes"

"encoding/base64"

"fmt"

"html/template"

"log"

"net/smtp"

)func

sendemail

(subject string

, to string

, smtphost string

, smtpport string

, username string

, password string

)error

//將資料傳入模版

data :=

struct

buf :=

new(bytes.buffer)

err = body.

execute

(buf, data)

if err !=

nil//準備郵件報文

email :=

"to: "

+ to +

"\n"

+"from: "

+ username +

"\n"

+"subject: "

+ subject +

"\n"

+"content-type: text/html; charset=utf-8"

+"\n"

+"content-transfer-encoding: base64"

+"\n\n"

+ base64.stdencoding.

encodetostring

(buf.

bytes()

) err = smtp.

sendmail

(fmt.

sprintf

("%s:%s"

, smtphost, smtpport)

, auth, username,

string,[

]byte

(email)

)if err !=

nilreturn

nil}

//-- main.go

//author: richard

package main

import

("fmt"

"test"

)//*** 需要填入自己的郵箱及密碼

func

main()

lang

="en"

>

>

charset

="utf-8"

>

>

titletitle

>

type

="text/css"

>

#header,#container,#footer

style

>

head

>

>

"header"

>

}div

>

"container"

>

div>

"footer"

>

div>

body

>

html

>

e=m

c2

e= mc^

e=mc

2參考文獻

[1]

golang傳送郵件

記錄實現golang傳送郵件功能遇到的問題 1.550 user has no permission 解決方法 在郵箱中開啟kehu 解決方法 在 中使用授權碼代替密碼 最終郵件傳送成功 3.修改為郵箱伺服器報錯 x509 certificate signed by unknown authorit...

Golang 使用gomail包傳送郵件

文件 示例 example package gomail 支援 go get gopkg.in gomail.v2import bytes fmt gopkg.in gomail.v2 html template strings time const mail template 3456p styl...

html傳送郵件 Python傳送郵件(三十)

簡單郵件傳輸協議 smtp 是一種協議,用於在郵件伺服器之間傳送電子郵件和路由電子郵件。python提供smtplib模組,該模組定義了乙個smtp客戶端會話物件,可用於使用smtp或esmtp偵聽器守護程式向任何網際網路機器傳送郵件。這是乙個簡單的語法,用來建立乙個smtp物件,稍後將演示如何用它...