nodejs——發送郵件(帶附件)

 用到的包是 nodemailer,簡單,有效。html

一、auth 中的 pass,是指「郵箱第三方登陸受權碼」,如何獲取受權碼,以QQ郵箱爲例,請點擊:http://jingyan.baidu.com/article/fedf0737af2b4035ac8977ea.htmlnode

二、若message中的text和html同時存在,收件方只顯示html內容。git

三、message.html 中能夠嵌套圖片,配置cid做爲圖片的惟一引用地址,指的是發送郵箱附件時設置的cid,以下例中,上傳的兩張圖片cid分別設置爲0001和0002,在message.html中img標籤scr屬性分別指向這兩個cid。github

四、支持國內的QQ、163等郵箱,具體還支持哪些郵箱服務,請點擊:https://github.com/nodemailer/nodemailer-wellknown/blob/master/services.jsonjson

五、如有用,請點個推薦~  :)app

 'use strict'

 var bunyan = require('bunyan');
 var nodemailer = require('nodemailer');

 var transporter = nodemailer.createTransport({
     service: 'QQ',
     auth: {
         user: '944xxxx69@qq.com',//發送者郵箱
         pass: 'czboxxxxxqvmbebd' //郵箱第三方登陸受權碼
     },
     logger: bunyan.createLogger({
         name: 'nodemailer'
     }),//打印日誌
     debug: true
 },{
     from: '944xxxx69@qq.com',//發送者郵箱
     headers: {
         'X-Laziness-level': 1000
     }
 });

 console.log('SMTP Configured');

 var message = {
     // Comma separated lsit of recipients 收件人用逗號間隔
     to: '12xxxx101@qq.com',

     // Subject of the message 信息主題
     subject:  'Nodemailer is unicode friendly',

     // plaintext body
     text: 'Hello to myself~',

     // Html body
     html: '<p><b>Hello</b> to myself <img src= "cid:00001"/></p>' + 
         '<p>Here\'s a nyan car for you as embedded attachment:<br/><img src="cid:00002"/></p>',

     // Apple Watch specific HTML body 蘋果手錶指定HTML格式
     watchHtml: '<b>Hello</b> to myself',

     // An array of attachments 附件
     attachments: [
         // String attachment
         {
             filename: 'notes.txt',
             content: 'Some notes about this e-mail',
             contentType: 'text/plain' // optional,would be detected from the filename 可選的,會檢測文件名
         },
         // Binary Buffer attchment
         {
             filename: 'image.png',
             content: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/' +
                '//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U' +
                'g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC', 'base64'),
             cid: '00001'  // should be as unique as possible 儘量惟一
         },
         // File Stream attachment
         {
             filename: 'nyan cat.gif',
             path: __dirname + '/appData/nyan.gif',
             cid: '00002'  // should be as unique as possible 儘量惟一
          }
     ]

 };

 console.log('Send Mail');
 transporter.sendMail(message, (error, info) => {
     if (error) {
         console.log('Error occurred');
         console.log(error.message);
         return;
     }
     console.log('Message sent successfully!');
     console.log('Server responded with "%s"', info.response);
     transporter.close();
 });

接收到的郵件結果:ui

相關文章
相關標籤/搜索