[Reprint] Outgoing mail components nodemailer--nodejs Middleware series

Source: Internet
Author: User

The zero-based NODEJS series article will show you how to benefit JavaScript as a server-side script through NODEJS Framework web development. The NODEJS framework is a V8-based engine and is the fastest JavaScript engine available today. The Chrome browser is based on V8, and opening 20-30 pages is a smooth one. The NODEJS Standard Web Development Framework Express helps us quickly build web sites that are more efficient than PHP and have a lower learning curve. Very suitable for small websites, personalization sites, our own Geek website!!

About the author

    • Zhang Dan (Conan), programmer Java,r,php,javascript
    • Weibo: @Conan_Z
    • Blog:http://blog.fens.me
    • Email: [Email protected]

Reprint please specify the source:
http://blog.fens.me/nodejs-email-nodemailer/

Objective

E-Mail is one of the most widely used services in Internet applications, and through the e-mail system, we can connect with Internet users in any corner of the world.

Using Nodejs to send and receive e-mails is also very simple, and the Nodemailer package can help you quickly implement the message.

Directory

    1. Nodemailer Package Introduction
    2. Send mail using Nodemailer
    3. Advanced use of outgoing mail
1. Nodemailer Package Introduction

Nodemailer is an easy-to-use node. JS mail delivery component with the GitHub project address Https://github.com/andris9/Nodemailer.

Key features of the Nodemailer include:

      • Support for Unicode encoding
      • Support Window System Environment
      • Supports HTML content and plain text content
      • Support Accessories (Transfer large attachments)
      • Supports embedding images in HTML content
      • Support for ssl/starttls secure mail delivery
      • Support for the built-in transport method and other plug-in implementations of the transport method
      • Support for custom plug-ins to process messages
      • Support for XOAUTH2 login verification

The above features, has covered most of the e-mail needs, then let us start to write the program.

2. Send mail using Nodemailer

My system environment

        • Win7 64bit
        • Node 0.10.5
        • NPM 1.2.19

First, create the project directory.

~ D:\workspace\javascript>mkdir nodejs-nodemailer && cd nodejs-nodemailer

New node project configuration file: Package.json

~ vi package.json{  "name": "nodejs-nodemailer",  "version": "0.0.1",  "description": "nodejs-nodemailer",  "keywords": [    "email"  ],  "author": "Conan Zhang <[email protected]>",  "dependencies": {    "nodemailer": "^1.2.1"  }}

Installing the Nodemailer Package

~ npm installnpm WARN package.json [email protected] No repository field.npm WARN package.json [email protected] No README data[email protected] node_modules\nodemailer├── [email protected] ([email protected], [email protected])├── [email protected] ([email protected], [email protected])├── [email protected] ([email protected], [email protected], [email protected])├── [email protected] ([email protected])└── [email protected] ([email protected], [email protected], [email protected])

Use the official example to send an email through a Gmail mailbox. Set up your email address [email protected] and send it to [email protected]. The code below is used to replace the content of XXXXX with its own content.

Create a new file Email.js

var nodemailer = require(‘nodemailer‘);var transporter = nodemailer.createTransport({    service: ‘Gmail‘,    auth: {        user: ‘[email protected]‘,        pass: ‘xxxxx‘    }});var mailOptions = {    from: ‘bsspirit <[email protected]>‘, // sender address    to: ‘[email protected]‘, // list of receivers    subject: ‘Hello ?‘, // Subject line    text: ‘Hello world ?‘, // plaintext body    html: ‘<b>Hello world ?</b>‘ // html body};transporter.sendMail(mailOptions, function(error, info){    if(error){        console.log(error);    }else{        console.log(‘Message sent: ‘ + info.response);    }});

Run the program

~ node email.jsMessage sent: 250 2.0.0 OK 1409797959 f1sm216864pdf.43 - gsmtp

Hit my 163 e-mail and receive the email you just sent. Mail Service is not always, sometimes a little bit slower, there may be a few minutes of delay.

At the same time, we can also find the email we just sent in Gmail's outbox.

We have mastered the basic operation of e-mail. Next, continue to introduce some advanced features.

3. Advanced use of e-mail

Nodemailer provides advanced features for sending e-mails, including:

        • CC and Bcc
        • Send Attachments
        • Send HTML-formatted content and embed images
        • Using a secure SSL channel

3.1 cc and Bcc

When sending a message, select the recipient, there are 3 options, TO,CC,BCC.

        • To: Is the recipient
        • CC: is a CC that notifies the relevant person that the recipient can see who sent the message to the CC. General return work or cross-departmental communication, will CC to the recipient's leader a copy
        • BCC: is a secret send, is also used to notify the relevant person, but the recipient is not see the message was sent to whom.

program implementation, modify the Mailoptions configuration parameters in the Email.js file, send to [email protected], CC to [email protected], secret to [email protected].

var mailOptions = {    from: ‘[email protected]>‘, // sender address    to: ‘[email protected]‘, // list of receivers    cc: ‘[email protected]‘,    bcc: ‘[email protected]‘,    subject: ‘Hello ?‘, // Subject line    text: ‘Hello world ?‘, // plaintext body    html: ‘<b>Hello world ?</b>‘ // html body};

3.2 Sending Attachments

Sending attachments is also a common feature of the messaging system, and Nodemailer supports a variety of attachment strategies. Next, we test to send two files as attachments.

File Text0.txt, as a string, as the body content of the file.
File Text1.txt, read the local file, as the body content of the file.

var mailOptions = {    from: ‘bsspirit <[email protected]>‘,    to: ‘[email protected]‘,    subject: ‘Hello ?‘,    text: ‘Hello world ?‘,    html: ‘<b>Hello world ?</b>‘ // html body    attachments: [        {            filename: ‘text0.txt‘,            content: ‘hello world!‘        },        {            filename: ‘text1.txt‘,            path: ‘./attach/text1.txt‘        }    ]};

View Inbox, 2 attachments are correct!

3.3 HTML-formatted content and embedded images

Nodemailer also provides us with the ability to embed images in the body of the HTML, as long as the CID is configured as the only reference address for the image. Upload a local image./img/r-book1.png, set CID to 00000001, and then in the body of the HTML, the img tag src attribute points to 00000001 CID on the line.

The code is as follows:

var mailOptions = {    from: ‘bsspirit <[email protected]>‘,    to: ‘[email protected]‘,    subject: ‘Embedded Image‘,    html: ‘<b>Hello world ?</b><br/>Embedded image: ‘,    attachments: [{        filename: ‘01.png‘,        path: ‘./img/r-book1.png‘,        cid: ‘00000001‘    }]}

Open the Inbox to view the message body content, and the picture is embedded in the body of the message.

3.4 Using a secure SSL channel

For the security of the contents of the message body, we usually encrypt the send to prevent the message from being intercepted by the intermediary server that the plaintext is routed during the network transmission. Most e-mail providers support SSL encrypted channels.

Gmail SSL Email configuration, I want to create a new transport variable stransporter, the configuration port for the 465,secureconnection property is set to True, you can refer to the following code:

var stransporter = nodemailer.createTransport({    service: ‘Gmail‘,    secureConnection: true, // use SSL    port: 465, // port    auth: {        user: ‘[email protected]‘,        pass: ‘xxxxxxxxx‘    }});function ssl(){    var mailOptions = {        from: ‘bsspirit <[email protected]>‘,        to: ‘[email protected]‘,        subject: ‘SSL Email‘,        html: ‘Hello world‘    }    return mailOptions;}stransporter.sendMail(ssl(), function(error, info){    if(error){        console.log(error);    }else{        console.log(‘Message sent: ‘ + info.response);    }});

Run the program

~ node email.jsMessage sent: 250 2.0.0 OK 1409807603 zs5sm478150pbb.83 - gsmtp

With a few lines of code, you can complete the function.

Nodemailer package provides us with a very simple e-mail API, so that we can use a few lines of code to complete the task of e-mail, greatly simplifying the learning cost of the mail protocol, improve the efficiency of development. But for a complete mail system, the receiving part of the mail is the most complex, send e-mail just give us practice practiced hand. When I find the appropriate collection of e-mail library, then the detailed introduction.

Reprint please specify the source:
http://blog.fens.me/nodejs-email-nodemailer/

[Reprint] Outgoing mail components nodemailer--nodejs Middleware series

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.