Go實現SMTP郵件發(fā)送訂閱功能(包含163郵箱、163企業(yè)郵箱、谷歌gmail郵箱)
前置
郵件模板
郵件模版類似如下圖發(fā)來的歡迎加入的模版

這里我們使用html格式存儲模版,上圖源碼如下
<html lang="en-US" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>email</title>
<style>
a{
color: #ECC94B !important;
}
.foot-text{
color: rgba(0, 0, 0, 0.50) !important;
}
.im{
color:rgba(0,0,0,0.86) !important;
}
.center {
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body style="background-color: white;">
<div style="width: 640px;height: auto;border-radius: 5px;margin: 0 auto;position: relative; padding-bottom: 80px; padding-top: 20px">
<div>
<img width="640" src="file:///Users/yanzhixing/Downloads/My/文檔/HatchfulExport-All/linkedin_banner_image_2.png" alt="">
</div>
<div style="color: rgba(0,0,0,0.86);font-family: 'Roboto','Century Gothic', 'Trebuchet MS', 'Hiragino Sans GB', 微軟雅黑, 'Microsoft Yahei', Tahoma, Helvetica, Arial, 'SimSun', sans-serif;font-size: 16px;margin: 10px auto 0px">
<h2 style="font-size: 20px;font-weight: 700; color: #000">Dear KunZhi Fans,</h2>
<div>
<p style="margin: 16px 0; ">Welcome to the family! We are glad to have you on board as a subscriber to my blog.</p >
<p style="font-weight: 600; color: #000;">Get the latest on <a style="color: #000" rel="external nofollow" rel="external nofollow" >CSDN</a> and give me a follow if you haven't already.</p>
<p style="margin: 16px 0">
<p style="font-weight: 600; color: #000">???? About Me</p>
<p style="margin-bottom: 8px">Former Alibaba programmer, now working for a blockchain company. He is a blogger in the domestic Internet circle, an expert blogger on Alibaba Cloud, and the manager of CSDN Hangzhou City Community. Welcome to communicate and win-win cooperation.</p>
</p >
<div style="margin: 16px 0">
<p style="font-weight: 600; color: #000;">?? Contact Me</p>
<p style=" margin-bottom: 8px">Should you have any questions, require assistance, or want to dive deeper into any aspect, you can reach out to me through various channels:</p>
<div>
<p style="margin-bottom: 0; display: flex; margin-bottom: 4px">
<span style="margin: 0 8px">●</span>
<span>Wechat: Follow me <a style="color: #ECC94B;text-decoration: none " target="_blank">kunzhi96</a> to communicate and learn together.</span>
<div class="center">
<img width="200" src="file:///Users/yanzhixing/Downloads/My/私人/微信二維碼.png" alt="">
</div>
</p>
<p style="margin: 0; display: flex; margin-bottom: 4px">
<span style="margin: 0 8px">●</span>
<span>CSDN Blog: Visit my blog -<a style="color: #ECC94B; text-decoration: none" target="_blank" rel="external nofollow" rel="external nofollow" >鯤志說</a> for in-depth information about my learning content and technology sharing.</span>
</p>
<p style="margin: 0; display: flex; margin-bottom: 4px">
<span style="margin: 0 8px">●</span>
<span> Email: Feel free to contact us via email at <span style="color: #ECC94B; opacity: 1;">XXX@163.com</span> for any inquiries, feedback, or support needs.</span>
</p>
</div>
<p style="margin-bottom: 0px">I'm excited to embark on this journey with you.</p>
</div >
<p>Warm regards,</p>
<p>Kun Zhi</p>
<div style="background-color: #F7F7F7; padding: 40px; text-align:center;">
<p style="font-size: 24px;font-weight: 700; color: #000; margin-bottom: 24px; margin-top: 0">KunZhi</p>
<p style="margin-bottom: 8px; margin-top: 0">This email was send to <span style="color: #ECC94B; opacity: 1;">xxx@gmail.com</span></p>
<p style="margin-bottom: 24px; margin-top: 0">You've received it because you've subscribed to our newsletter.</p>
<div>
<a style="color: rgba(0, 0, 0, 0.50); text-decoration: underline" href="unsubscribe_url/unsubscribe?email=unsubscribe_email" rel="external nofollow" class="foot-text">Unsubscribe</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>郵箱開啟SMTP服務
選擇好官方郵箱來開啟smtp服務,這里我測試驗證了163郵箱、163企業(yè)郵箱、谷歌gmail郵箱和騰訊企業(yè)郵箱(但騰訊企業(yè)郵箱未成功,后續(xù)會說明)
163郵箱
- 登錄163郵箱(一定不要登錄到簡易版?。?/li>
- 登錄后如下圖所示,點擊上面導航欄的設置

- 按照下圖順序點擊 POP3/SMTP/IMAP

- 開啟SMTP服務
如下圖我已經是開啟狀態(tài)了

- 新增授權密碼
如上圖,我們如果需要使用SMTP服務,就一定要使用授權碼,而且這個密碼只出現一次,一定要記得保存好,保存好先留著,我們后面會用到
- 服務器地址及端口
我們使用的是SMTP服務,則對應的服務器地址是smtp.163.com,端口為25,后面都會用到

自此,163郵箱的smtp服務開啟完畢,可直接跳到郵件發(fā)送源碼處繼續(xù)即可
163企業(yè)郵箱
可以看到登錄的是網易靈犀辦公界面

登錄后如下圖所示,點擊上面導航欄的設置-賬號與安全-客戶端設置

- 進入客戶端設置
可看到如下圖
- 選擇IMAP協(xié)議
- 開啟并設置客戶端授權密碼

- 新增授權密碼
如上圖,生成授權碼,而且這個密碼只出現一次,一定要記得保存好,保存好先留著,我們后面會用到。
可以看到163企業(yè)郵箱不同的是,有一個到期時間,也就意味著,到期了,我們需要更換授權碼,這一點需要謹記
- 服務器地址及端口
我們使用的是SMTP服務,則對應的服務器地址是smtphz.qiye.163.com,端口為25,后面都會用到

自此,163企業(yè)郵箱的smtp服務開啟完畢,可直接跳到郵件發(fā)送源碼處繼續(xù)即可
谷歌gmail郵箱
登錄 谷歌gmail郵箱
點擊設置-查看所有設置

點擊轉發(fā)和 POP/IMAP 標簽頁,如下圖進行啟用設置,并保存更改

- 創(chuàng)建和使用應用專用密碼
- 前往您的 Google 帳號-選擇安全性
- 在“登錄 Google”下方,選擇兩步驗證

- 在頁面底部,選擇應用專用密碼,進行點擊

- 輸入一個名稱,以幫助您記住在什么情況下使用應用專用密碼,如我的kunzhi-test

- 選擇創(chuàng)建后,會出現如下彈窗。設備的應用專用密碼即生成了,是指在設備上生成的 16 個字符的代碼。也就是授權碼,而且這個密碼只出現一次,一定要記得保存好,保存好先留著,我們后面會用到。

- 選擇完成,記得應用名稱對應的密碼即可

- 服務器地址及端口
我們使用的是SMTP服務,則對應的服務器地址是smtp.gmail.com,端口為587,后面都會用到

自此,谷歌gmail郵箱的smtp服務開啟完畢,可直接跳到郵件發(fā)送源碼處繼續(xù)即可
騰訊企業(yè)郵箱-失敗
騰訊企業(yè)郵箱失敗的原因是因為一直沒有找到授權碼在哪里進行設置,同時使用郵箱的密碼作為授權碼也無法發(fā)送郵件,所以一直沒有實現,但是前面的操作步驟可以放出來供大家參考,如果有人找到了騰訊企業(yè)郵箱的操作方法請一定要評論區(qū)給出解法。

其他郵箱-未操作
這個鏈接的操作我并未實際執(zhí)行,需要的可以參考
發(fā)件服務設置-包含:阿里云郵箱設置、Outlook郵箱設置
郵件發(fā)送核心代碼
config.yaml配置
這里是發(fā)送郵件的郵箱相關配置,這里就使用到之前只出現一次的授權碼了,以及對應的服務器地址和端口
email: # 163郵箱 template_dir: /test.html smtp_server: smtp.163.com smtp_port: 25 smtp_user: KunZhi smtp_password: 授權碼 from_email: XXXX@163.com # 騰訊企業(yè)郵箱 # smtp_server: smtp.exmail.qq.com # smtp_port: 465 # smtp_user: KunZhi # smtp_password: 授權碼 # from_email: XXXX # 163企業(yè)郵箱 # smtp_server: smtphz.qiye.163.com # smtp_port: 25 # smtp_user: KunZhi # smtp_password: 授權碼 # from_email: XXXX # gmail # smtp_server: smtp.gmail.com # smtp_port: 587 # smtp_user: KunZhi # smtp_password: 授權碼 # from_email: XXXX@gmail.com
這里的smtp_user如下圖,就是展示的發(fā)件人名稱

讀取郵件相關配置
//讀取郵件相關配置
err = sendWelcomeEmail(Cfg{
SenderAddress: viper.GetString("email.from_email"),
SenderName: viper.GetString("email.smtp_user"),
SenderPwd: viper.GetString("email.smtp_password"),
MailServerHost: viper.GetString("email.smtp_server"),
MailServerPort: viper.GetString("email.smtp_port"),
}, viper.GetString("email.from_email"), toEmail, unsubscribeUrl)
if err != nil {
errors.Errorf("Failed to send email: ", toEmail, err)
responseData := gin.H{
"message": "Failed to send email: " + toEmail,
"code": -1,
}
c.JSON(http.StatusOK, responseData)
return err
}發(fā)送郵件
func sendWelcomeEmail(cfg Cfg, template string, recipientEmail, unsubscribeUrl string) error {
currentDir, err2 := os.Getwd()
if err2 != nil {
log.Fatalf("Failed to get current working directory: %v", err2)
}
//獲取郵件模版
htmlContent, err3 := ioutil.ReadFile(currentDir + viper.GetString("email.template_dir"))
if err3 != nil {
fmt.Println("Failed to read HTML file:", err3)
return err3
}
// 郵件標題
subject := "Your Journey Begins Here"
message := string(htmlContent)
// 需要替換郵件模版中的字符串映射
replacements := map[string]string{
"xxx@gmail.com": recipientEmail,
"header_img": viper.GetString("img.header_img"),
}
// 替換字符串
for oldStr, newStr := range replacements {
message = strings.Replace(message, oldStr, newStr, -1) // -1 表示替換所有匹配項
}
// 連接到 SMTP 服務器并發(fā)送電子郵件
auth := smtp.PlainAuth("", cfg.SenderAddress, cfg.SenderPwd, cfg.MailServerHost)
to := []string{recipientEmail}
msg := []byte("To: " + recipientEmail + "\r\n" +
"Subject: " + subject + "\r\n" +
"From: " + cfg.SenderName + " <" + cfg.SenderAddress + ">\r\n" +
"MIME-Version: 1.0\r\n" +
"Content-Type: text/html; charset=utf-8\r\n" + // 將內容類型設置為 HTML
"\r\n" + message)
//發(fā)送郵件
err := smtp.SendMail(cfg.MailServerHost+":"+cfg.MailServerPort, auth, cfg.SenderAddress, to, msg)
if err != nil {
fmt.Println("failed to send email:", err)
return err
}
return nil
}如上代碼,可以實現SMTP郵件發(fā)送訂閱功能
以上就是Go實現SMTP郵件發(fā)送訂閱功能(包含163郵箱、163企業(yè)郵箱、谷歌gmail郵箱)的詳細內容,更多關于Go實現SMTP郵件發(fā)送的資料請關注腳本之家其它相關文章!

