Home >Web Front-end >JS Tutorial >Using Node.JS to implement email sending function

Using Node.JS to implement email sending function

高洛峰
高洛峰Original
2016-12-09 13:43:141447browse

Step one, configuration

First you need to install the nodemailer library

npm install nodemailer//默认会安装最新的版本。

For the documentation about this library, please see nodemailer

Step two, some introduction to the use of the library

The method of using this library is very simple. The first thing is to create an instance for sending emails

var transporter = nodemailer.createTransport(transport[, defaults])

transport parameter attribute

There are too many attributes, so just write some key attributes

 port: The port number of the connection, usually 465

host: The host of the server you use to send emails. For example, the host of 163 is stmp.163.com

auth: This is the difference from the old version. The new version uses a literal to store username and password. Note that stmp must be enabled in your mailbox.

user: username

pass: password. If your 163 has set a third-party login password, you need to fill in your third-party login password here.

After setting these, you can use it~ Paste my settings here

var smtpConfig = {
 host: 'smtp.163.com',
 port: 465,
 auth: {
  user: 'xxxx',
  pass: 'xxxx'
 }
};
var transporter = nodemailer.createTransport(smtpConfig);

The third step, Usage

Now we can use the following function to send emails

transporter.sendMail(data[, callback])

data email content

from the sender of the email

to the recipient of the email

subject subject

text The email is sent as text

html The content of the email is the html webpage effect

attachments attachments. For details, please see the official documentation

callback function

Accepts two parameters err and info

err

If it fails, you can print this object to see relevant information

info

You can see a lot of sending status information

E Messageid will return the messageid value of information, and I don't know much about


Accepts are an array, including the address of the content of the server receiving content


Rejection is similar to that of the above, that is, the opposite meaning


After that, we are finished. You can send the email

var sendmail = function(html){
 var option = {
  from:"sender",
  to:"accepter",
  subject : '来自node的邮件',
  html : html
 }
 transporter.sendMail(option, function(error, response){
  if(error){
   console.log("fail: " + error);
  }else{
   console.log("success: " + response.messageID);
  }
 });
}
 
sendmail("邮件内容:<br/>这是来自nodemailer发送的邮件");


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn