Node.js 测试 SMTP 服务

2022-08-06 17:03:31 浏览数 (1)

本文记录 Node.js 脚本测试 SMTP 的两种方法。

Node.js 测试 SMTP

  • node 脚本可以使用 node xxx.js 执行
  • 如果有包找不到,可以使用命令安装
代码语言:javascript复制
npm install --save <package_name>

方法一

  • 使用 net 包,建立连接
  • 示例代码(账号使用的是测试账号,可以直接运行)
代码语言:javascript复制
const net = require('net')
const assert = require('assert')

const host = 'smtp.zywvvd.com',
      port = 25,
      user = 'test@zywvvd.com',
      pass = '12345678',
      to = 'test@zywvvd.com',
      subject = '测试邮件',
      msg = `这是一封来自node的邮件`

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}rn`)
    sendData(`${msg}rn.`)

    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 'rn')
}

let data = null
client.on('data', d => {
    console.log('接受到: ' d.toString())
    data = d.toString().substring(0,3)
})
client.on('end', () => {
    console.log('连接断开')
})

  • 直接运行,输出结果:
代码语言:javascript复制
接受到: 334 VXNlcm5hbWU6

test.js:87
发送: dGVzdEB6eXd2dmQuY29t
test.js:81
(node:13692) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
test.js:28
接受到: 334 UGFzc3dvcmQ6

test.js:87
发送: MTIzNDU2Nzg=
test.js:81
接受到: 235 2.7.0 Authentication successful

test.js:87
发送: MAIL FROM:<test@zywvvd.com>
test.js:81
接受到: 250 2.1.0 Ok

test.js:87
发送: RCPT TO:<test@zywvvd.com>
test.js:81
接受到: 250 2.1.5 Ok

test.js:87
发送: DATA
test.js:81
接受到: 354 End data with <CR><LF>.<CR><LF>

test.js:87
发送: SUBJECT:测试邮件
test.js:81
发送: FROM:test@zywvvd.com
test.js:81
发送: TO:test@zywvvd.com

test.js:81
发送: 这是一封来自node的邮件
.
test.js:81
接受到: 250 2.0.0 Ok: queued as 6FB8F11E79F

test.js:87
发送: QUIT
test.js:81
接受到: 221 2.0.0 Bye

test.js:87
连接断开
test.js:91

  • 登录邮箱: 101.43.39.125
  • 成功收到测试邮件

方法二

  • 使用 nodemailer 工具
  • Nodemailer 是一个简单易用的 Node.JS 邮件发送模块(通过 SMTP,sendmail,或者 Amazon SES),支持 unicode,你可以使用任何你喜欢的字符集。
  • Github: https://github.com/nodemailer/
  • 官方链接: https://nodemailer.com/about/
  • nodemailer 支持很多自定义的服务器,列表链接:https://nodemailer.com/smtp/well-known/

当前支持的服务 "126", "163", "1und1", "AOL", "DebugMail", "DynectEmail", "FastMail", "GandiMail", "Gmail", "Godaddy", "GodaddyAsia", "GodaddyEurope", "hot.ee", "Hotmail", "iCloud", "mail.ee", "Mail.ru", "Maildev", "Mailgun", "Mailjet", "Mailosaur", "Mandrill", "Naver", "OpenMailBox", "Outlook365", "Postmark", "QQ", "QQex", "SendCloud", "SendGrid", "SendinBlue", "SendPulse", "SES", "SES-US-EAST-1", "SES-US-WEST-2", "SES-EU-WEST-1", "Sparkpost", "Yahoo", "Yandex", "Zoho", "qiye.aliyun"

  • 示例代码(以QQ为例,需要去QQ邮箱开启 IMAP/SMTP 服务并申请授权码)
代码语言:javascript复制
'use strict';

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
  // host: 'smtp.ethereal.email',
  service: 'qq', // 使用了内置传输发送邮件 查看支持列表:https://nodemailer.com/smtp/well-known/
  port: 465, // SMTP 端口
  secureConnection: true, // 使用了 SSL
  auth: {
    user: 'xxxxxxx@qq.com',
    // 这里密码不是qq密码,是你设置的smtp授权码,去qq邮箱后台开通、查看
    pass: 'xxxxxxxxxxxx',
  }
});

let mailOptions = {
  from: '"Rogn" <xxxxxxx@qq.com>', // sender address
  to: 'xxxxxxx@qq.com', // list of receivers
  subject: 'Hello', // Subject line
  // 发送text或者html格式
  // text: 'Hello world?', // plain text body
  html: '<h1>Hello world</h1>' // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    return console.log(error);
  }
  // console.log('Message sent: %s', info.messageId);
  console.log(info)
});

  • 成功收到邮件:

参考资料

  • https://baijiahao.baidu.com/s?id=1708845406356492948&wfr=spider&for=pc

0 人点赞