current position:Home>Node.js test SMTP service

Node.js test SMTP service

2022-08-06 18:32:03why why

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

Node.js 测试 SMTP

  • node 脚本可以使用 node xxx.js 执行
  • If there is a package not found,可以使用命令安装
npm install --save <package_name>

方法一

  • 使用 net 包,建立连接
  • 示例代码(The account used is a test account,可以直接运行)
const net = require('net')
const assert = require('assert')

const host = 'smtp.zywvvd.com',
      port = 25,
      user = '[email protected]',
      pass = '12345678',
      to = '[email protected]',
      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}`)
    // sender
    sendData(`FROM:${user}`)    
    // target
    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('连接断开')
})

  • 直接运行,输出结果:
接受到: 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:<[email protected]>
test.js:81
接受到: 250 2.1.0 Ok

test.js:87
发送: RCPT TO:<[email protected]>
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:[email protected]
test.js:81
发送: TO:[email protected]

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
  • 成功收到测试邮件

方法二

Currently supported services "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 service and request an authorization code)
'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: '[email protected]',
    // 这里密码不是qq密码,是你设置的smtp授权码,去qqThe mailbox background is opened、查看
    pass: 'xxxxxxxxxxxx',
  }
});

let mailOptions = {
  from: '"Rogn" <[email protected]>', // sender address
  to: '[email protected]', // 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)
});

  • 成功收到邮件:

参考资料

copyright notice
author[why why],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/218/202208061814417651.html

Random recommended