1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| var MailParser = require('mailparser').MailParser var Imap = require('imap') var Path = require('path') var fs = require('fs') var dayjs = require('dayjs')
function QQ() { const imap = new Imap({ /** QQ 邮箱 */ user: 'XXXXXXX@qq.com', /** 这里填写的不是 QQ邮箱的密码,这里是 pop3 的密钥 */ password: 'XXXXXXXX', host: 'pop.qq.com',
tls: false, authTimeout: 1000, tlsOptions: { rejectUnauthorized: false }, }) const search = () => imap.search( [ [ 'UNSEEN', ['SINCE', new Date(+new Date() - 5 * 60 * 1000).toISOString()], ], ], (err, results) => { if (!err) { try { const f = imap.fetch(results, { markSeen: false, bodies: '', struct: true, }) f.on('message', (msg) => { const mailparser = new MailParser() const info = { theme: '', form: '', mailName: '', to: '', datatime: '', html: null, text: null, uid: null, buffer: null, } let status = 0 const next = (data) => { imap.setFlags([data.uid], 'SEEN', () => {}) /** 这里拿到的 data 可以直接进行数据库存储 */ console.log(1111, data) } msg.on('body', (stream) => { stream.pipe(mailparser) mailparser.on('headers', (headers) => { info.theme = headers.get('subject') info.form = headers.get('from').value[0].address info.mailName = headers.get('from').value[0].name info.to = headers.get('to').value[0].address info.datatime = dayjs(headers.get('date')).format( 'YYYY-MM-DD HH:mm:ss' ) status++ if (status === 3) { next(info) } }) mailparser.on('data', (data) => { if (data.type === 'text') { status++ info.html = data.html info.text = data.text if (status === 3) { next(info) } } if (data.type === 'attachment') { const path = Path.join( __dirname, '..', '..', '..', '..', 'public', 'mailer', `${new Date().valueOf()}.${ data.filename.split('.')[ data.filename.split('.').length - 1 ] }` ) const ws = fs.createWriteStream(path) ws.on('close', () => { status++ info.buffer = fs.readFileSync(path) fs.unlinkSync(path) if (status === 3) { next(info) } }) data.content.pipe(ws) data.release() } }) }) msg.on('attributes', (data) => { info.uid = data.uid status++ if (status === 3) { next(info) } }) }) } catch (err) {} } else { throw err } } ) let init = true imap.once('ready', () => { imap.openBox('INBOX', true, (err) => { if (!err) { init = false search() } else { throw err } }) }) imap.on('mail', () => { if (!init) { search() } }) imap.connect() }
QQ()
|