一、前言
最近公司有個需求,在微信小程序中點擊后發送郵件到指定地址,並帶附件。要求用雲開發處理,不用本地的服務器。
參考了網上的一些資料,並動手做了測試,成功實現。
以下是一些博客的鏈接:
https://blog.csdn.net/tiramisu_ljh/article/details/78580635
https://www.jianshu.com/p/f8d330d9911a
https://blog.csdn.net/a446362429/article/details/105527425/ (注意:path的路徑)
用到的是node.js的nodemailer郵件發送模塊,安裝時要注意,用npm安裝。如果用cnpm安裝會有問題
代碼如下:
//引入發送郵件的類庫 let nodemailer = require('nodemailer'); //創建一個SMTP客戶端配置 let config = { host: "smtp.163.com" //郵箱的主機 ,prot: 465 //郵箱的端口號 ,secure: true//啟用SSL協議 465端口true,其他端口false,看的官方文檔 ,auth: { user: "xxxxxxx@163.com" //郵箱 ,pass: "KAQTZUNDDXFNZNNW" //郵箱授權碼或密碼 } } //創建SMTP客戶端對象 let transporter = nodemailer.createTransport(config); let mail = { from: 標題+"<xxxxxxx@163.com>" //發件人,里面的郵箱必須填寫正確,否則會有問題 ,subject: '郵件' //郵件主題 ,to: 'xxxxxxx@163.com' // 收件列表,可以多個,也就是群發,用逗號","隔開 ,text: "" //發送文本 ,html: "請查收附件" //發送html代碼 ,attachments: [{}]//附件,格式為{filename,path} } let res = transporter.sendMail(mail);