郵件的協議smtp是tcp/ip族中的一個協議,所以我們這次考慮使用net模塊來發送郵件。
const net = require('net')
const assert = require('assert')
const host = 'smtp.163.com',
port = 25,
user = 'zhangjunyi199616@163.com',
pass = '*********',
to = '442665319@qq.com',
subject = '少林武當大叮當',
msg = `你好,張啊咩同學,我是一封來自node的郵件
愛你喲123
`
let client = net.createConnection({host,port},async() => {
console.log('連接上了')
let code
code = await getData()
assert(code == 220)
// 打招呼
sendData('HELO ' + host)
code = await getData()
assert(code == 250)
// 要登陸
sendData('auth login')
code = await getData()
assert(code == 334)
// 給用戶名(郵箱)---base64編碼
sendData(new Buffer(user).toString('base64'))
code = await getData()
assert(code == 334)
// 給密碼---base64編碼
sendData(new Buffer(pass).toString('base64'))
code = await getData()
assert(code == 235)
// 給用戶名(郵箱
sendData(`MAIL FROM:<${user}>`)
code = await getData()
assert(code == 250)
// 給目標郵箱
sendData(`RCPT TO:<${to}>`)
code = await getData()
assert(code == 250)
// 要發送數據
sendData('DATA')
code = await getData()
assert(code == 354)
// 發主題
sendData(`SUBJECT:${subject}`)
// 發發件人
sendData(`FROM:${user}`)
// 發目標
sendData(`TO:${to}\r\n`)
sendData(`${msg}\r\n.`)
code = await getData()
sendData(`QUIT`)
})
function getData() {
return new Promise((resolve,reject) => {
next()
function next(){
if(data) {
let temp = data
data =null
resolve(temp)
} else {
setTimeout(next,0)
}
}
})
}
function sendData(msg) {
console.log('發送:'+msg)
client.write(msg+'\r\n')
}
let data = null
client.on('data', d => {
console.log('接受到:'+d.toString())
data = d.toString().substring(0,3)
})
client.on('end', () => {
console.log('連接斷開')
})
過程:
連接上了 接受到:220 163.com Anti-spam GT for Coremail System (163com[20141201]) 發送:HELO smtp.163.com 接受到:250 OK 發送:auth login 接受到:334 dXNlcm5hbWU6 發送:emhhbmdqdW55aTE5OTYxNkAxNjMuY29t 接受到:334 UGFzc3dvcmQ6 發送:emhhbmc4NjQ3NzY2MA== 接受到:235 Authentication successful 發送:MAIL FROM:<zhangjunyi199616@163.com> 接受到:250 Mail OK 發送:RCPT TO:<442665319@qq.com> 接受到:250 Mail OK 發送:DATA 接受到:354 End data with <CR><LF>.<CR><LF> 發送:SUBJECT:少林武當大叮當 發送:FROM:zhangjunyi199616@163.com 發送:TO:442665319@qq.com 發送:你好,張啊咩同學,我是一封來自node的郵件 愛你喲123 . 接受到:250 Mail OK queued as smtp7,C8CowAC3Xh8MErdaVr+lLw--.64772S2 1521947148 發送:QUIT 接受到:221 Bye 連接斷開
