天天看點

node 發送接收郵件

node發送接收郵件

  • nodemailer
  • mailparser

nodemailer官網:https://nodemailer.com/about/

mailparser官網:https://www.npmjs.com/package/mailparser

/**
 *
 * @Description 郵件發送
 *
 */
const { lowdb } = require('../../db/lowdb/index')
var nodemailer = require('nodemailer')
var smtpTransport = require('nodemailer-smtp-transport')
const config = lowdb.read().value()

if (config.email.type === 'company') {
  // 公司郵箱
  smtpTransport = nodemailer.createTransport(
    smtpTransport({
      host: config.email.host,
      secureConnection: true,
      port: Number(config.email.port),
      auth: {
        user: config.email.user,
        pass: config.email.pass
      }
    })
  )
} else if (config.email.type === 'personal') {
  // 個人郵箱
  smtpTransport = nodemailer.createTransport(
    smtpTransport({
      service: config.email.service,
      auth: {
        user: config.email.user,
        pass: config.email.pass
      }
    })
  )
}


var Imap = require('imap');
var inspect = require('util').inspect;
var Mailparser = require('mailparser').MailParser;
var fs = require('fs');

var imap = new Imap({
  user: '[email protected]',
  password: 'gpaplixtsihocacj',
  host: 'imap.qq.com',
  port: 993,
  tls: true,
  tlsOptions: { rejectUnauthorized: false },
});

function openIndex(cb) {
  imap.openBox('INBOX', true, cb);
}

/**
 * @param {String} recipient 收件人
 * @param {String} subject 發送的主題
 * @param {String} html 發送的html内容
 */

const sendMail = function (recipient, subject, html) {
  smtpTransport.sendMail(
    {
      from: config.email.user,
      to: recipient,
      subject: subject,
      html: html
    },
    function (error, response) {
      if (error) {
        console.log(error)
        return error
      }
      console.log('發送成功')
      return true
    }
  )
}

const sendVerifyCodeMail = function (recipient, subject, code) {
  return new Promise((resolve, reject) => {
    smtpTransport.sendMail(
      {
        from: config.email.user,
        to: recipient,
        subject: subject,
        html: `
        <div class="juejin-reset" style="
            width: 600px;
            margin-left: auto;
            margin-right: auto;
            text-align: left;
            font-size: 14px;
            box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
        ">
                <div class="header" style="
                    height: 60px;
                    padding: 10px 60px;
                    border-bottom: 1px solid #eaeaea;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    box-sizing: border-box;
                ">
                    <a style="height: 40px;width: 100px;background: url() no-repeat 0 0;background-size: contain;" target="_blank" href="" target="_blank" rel="external nofollow"  class="home-link">
                    </a>
                    <div class="header__slogan" style="font-size: 14px;line-height: 40px;height: 40px;">${config.website.website_name}</div>
                </div>
                <div class="content" style="
                    line-height: 25px;
                    padding: 40px 60px;
                ">
                    <div style="font-weight:bold">HI:${recipient}</div>
                    <div>
                        <h2 style="color:#333">${code} </h2>
                    </div>
                     <div>驗證碼有效期為30分鐘</div>
                </div>
        </div>
        `
      },
      function (error, response) {
        if (error) {
          reject({
            state: 'error',
            message: error.response
          })
        }
        resolve({
          state: 'success',
          message: '發送成功'
        })
      }
    )
  })
}
// 接收郵件
const getMail = function (recipient, subject, html) {

  imap.once('ready', function() {
    
    openIndex(function(err, box){
      
        //郵件搜尋: 2015/7/28以後未讀的
        imap.search(['UNSEEN', ['SINCE', 'April 11, 2021']], function(err, results){
          
            if(err) console.log( err );
            
            var f = imap.fetch(results, {
 
            	bodies: '',
            	struct: true
            });
            
 
            f.on('message', function(msg, seqno){
                 var prefix = '(#' + seqno + ')' ;
                 
                 msg.on('body', function(stream, info){
                      
                      if(info.which === 'TEXT') {
                      	// console.log(prefix + 'Body [%s] found, %d total bytes',inspect(info.which), info.size) ;
                      }
 
                      var mailparser = new Mailparser();

                      stream.pipe(mailparser);

                      mailparser.on("headers", function(headers) {
                        //headers是Map類型
                            console.log("郵件主題: " + headers.get('subject'));
                             console.log("發件人: " + headers.get('from').text);
                            console.log("收件人: " + headers.get('to').text);
                            });
                            //當郵件頭部流全部傳入mailparser後觸發
                            
                            mailparser.on("data", function(data) {
                                //data是對象
                                if (data.type === 'text') {
                                  console.log("郵件内容: " + data.html);
                                }
                                if (data.type === 'attachment') {
                                  console.log("附件名稱:"+data.filename);
                                   data.content.pipe(fs.createWriteStream(data.filename)); 
                                   
                                  //儲存附件到目前目錄下
                                  data.release();
                                }
                      });
                 });
 
                 msg.once('attributes', function(attrs){
                    //  console.log(prefix + 'Attributes: %s',inspect(attrs,false,8));
                 });
 
                 msg.once('end', function(){
                    //  console.log(prefix + 'Finished');
                 });
            });
 
            f.once('error', function(err){
                  // console.log('Fetch error: '+err);
            });
 
            f.once('end', function(){
                  // console.log('Done fetching all messages!');
                  imap.end();
            });
        });
    });
});
 
imap.once('error', function(err){
      console.log(err)   
});
 
imap.once('end', function(){
      console.log('Connection ended');
});
 
imap.connect();
}

module.exports = {
  sendMail,
  getMail,
  sendVerifyCodeMail
}

// router.post( '/article/sendMail', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articles.sendMail )//sendMail

// static async sendMail (ctx) {
//   try {
    
//     let result = sendMail("[email protected]","測試發送","<p>你好,測試發送</p>")
//     console.log('----------------------------',result)
//     getMail()
//     console.log("****************************")

//   } catch (err) {
//     resAdminJson(ctx, {
//       state: 'error',
//       message: '錯誤資訊:' + err.message
//     })
//   }
// }

           

繼續閱讀