peri hokiperihokiclarustologisticsrimashaop.comangelpaintingtools.co.invrjanaenergies.comgates of olympus perihoki jadi mesin uang paling gacortrik main baccarat perihoki ala pro bikin pemula jadi jutawanpantang pulang sebelum jackpot main dadu sicbo perihokipgsoft mahjong ways 2 muncul scatter merah tiap spin perihokicara menciptakan akun perihokigacor mahjong wins 3jackpot kembar mahjong wins 3 abc1131cara menang stabil rtp mahjong ways abc1131bu nurlina menang 197 juta mahjong ways 2mahasiswa cuan 421 juta karena pola mahjongpemilik warung menang 128 juta mahjong wins 3strategi bravy erika mahjong abc1131 terungkappemuda jambi taklukkan mahjong wins 3penjual jamu menang besar mahjong wins 5pemuda kampung raup 180 juta mahjong wayskisah inspiratif petani mahjong ways keberhasilanmahasiswa menang 92 juta mahjong waysmodal warung kopi bang ojak sukses mahjong waystanpa modal maxwin mahjong wins 3 strategibocoran mahjong ways spin kombinasicara bermain mahjong untuk meraih keberuntungankeajaiban mahjong kasir indomaret sukses beli tanahmeraup keuntungan maksimal di mahjong winsid rahasia scatter hitamid pola scatterid jackpot mahjong waysid spin mahjong winsid tips jitu mahjongrahasia kemenangan mahjong ways spin slow

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 282

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_cookie_params(): Cannot change session cookie parameters when headers already sent

Filename: Session/Session.php

Line Number: 294

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 304

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 314

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 315

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 316

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 317

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 375

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: drivers/Session_files_driver.php

Line Number: 108

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_save_handler(): Cannot change save handler when headers already sent

Filename: Session/Session.php

Line Number: 110

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_start(): Cannot start session when headers already sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

Cách gửi mail trong NodeJS có file đính kèm
CĂN BẢN
SERVER
MYSQL
MONGODB
MODULE
CÁC CHỦ ĐỀ
BÀI MỚI NHẤT
MỚI CẬP NHẬT

Cách gửi mail trong NodeJS có file đính kèm

NodeJS là một trong những backend framework phổ biến nhất hiện nay. Với ưu điểm tốc độ nhanh, kho thư viện đồ sộ và đặc biệt là cộng đồng hỗ trợ rất đông đảo.

test php

banquyen png
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Trong hầu hết các dự án, tính năng thông báo tới người dùng, cụ thể là gửi email là một trong những tính năng quan trọng, và hầu như bắt buộc phải có. Bài viết hôm nay, mình sẽ hướng dẫn cách gửi email (có hỗ trợ đính kèm file) trong dự án NodeJS.

Khi đọc đến bài viết này, mình tin chắc rằng bạn đã biết và nguyên lý hoạt động cũng như ưu điểm nổi bật của nó. Thế nên mình sẽ không đi vào định nghĩa nhiều nữa nhé.

Giới thiệu NodeMailer

Trong rất nhiều thư viện về mail, mình đã lựa chọn Nodemailer, là một thư viện gửi mail phổ biến nhất cho NodeJS.

Bài viết này được đăng tại [free tuts .net]

Một số ưu điểm chính của nodemailer:

  • Viết hoàn toàn pure Javascript, không sử dụng thêm bất kỳ dependencies nào khác
  • Hỗ trợ SSL/TLS để bảo mật khi gửi email.
  • Hỗ trợ email transport thông qua các dịch vụ nổi tiếng như Amazon SES, Sendgrid,v.v...
  • Dễ dàng thêm file đính kèm trong mail. Đây là điểm khác biết so với các thư viện khác.

Phần tiếp theo, chúng ta sẽ cùng nhau thực hành gửi email có file đính kèm bằng nodemailer nhé.

Cài đặt Nodemailer

Cũng giống như các thư viện khác, chúng ta tiến hành cài đặt bằng câu lệnh đơn giản sau:

npm i nodemailer

Sau khi cài thành công, package,json sẽ tự động lưu thông tin của thư viện, kiểu như sau:

{
  "name": "express_website",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.15.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.2.0",
    "express": "~4.13.4",
    "nodemailer":"*"
  }
}

Khởi tạo transport

Như mình đã đề cập ở trên, nodemailer có hỗ trợ transport để sử dụng các dịch vụ bên thứ 3 để gửi mail như: Amazon SES, Sendgrid, Mailgun, SMTP,v.v.... Điều này rất là tiện, bởi vì bạn sẽ không cần phải dựng lại một mail server vô cùng phức tạp.

Trong ví dụ này, chúng ta sẽ sử dụng SMTP transport:

import nodemailer from "nodemailer";

const smtpTransport = nodemailer.createTransport({
  host: "smtp.example.com",
  port: 587,
  secure: false,
  auth: {
    user: "username",
    pass: "password",
  },
});

Cấu hình và khởi tạo email

Chúng ta có thể tạo một body của email gồm các thông tin như: địa chỉ email nhận, địa chỉ email gửi, tiêu đề, nội dung email.v.v...

const mailBody = {
  from: "username@gmail.com",
  to: "receiver@gmail.com",
  subject: "Sample email sent using nodemailer",
  html: "<h1>Hello World!</h1>"
};

Để thêm file đính kèm, cũng rất đơn giản! Nodemailer hỗ trợ rất nhiều kiểu đính kèm file như: base64, file path, stream,v.v... Bạn có thể tham khảo tài liệu chính thức của thư viện để có danh sách đầy đủ các loại đính kèm được hỗ trợ.

Trong bài viết này, mình sẽ sử dụng file path. Vì vậy, mình sẽ sửa lại body của mail một chút.

const mailBody = {
  from: "username@gmail.com",
  to: "receiver@gmail.com",
  subject: "Sample email sent using nodemailer",
  html: "<h1>Hello World!</h1>"
  attachments: [
        {
            filename: 'sample_attachment.png',
            path: __dirname + '/sample_attachment.png',
        }
    ]
};

Gửi email

Sau khi đã chuẩn bị xong hết cấu hình, nội dung email thì gọi hàm sendMail() để gửi email thôi.

smtpTransport.sendMail(mailBody, function (error, info) {
    if (error) {
        console.log(error);
    }

    console.log("Email with attachment delivered successfully")
});

Dưới đây là toàn bộ nội dung code:

import nodemailer from "nodemailer";

const smtpTransport = nodemailer.createTransport({
  host: "smtp.example.com",
  port: 587,
  secure: false,
  auth: {
    user: "username",
    pass: "password",
  },
});

const mailBody = {
  from: "username@gmail.com",
  to: "receiver@gmail.com",
  subject: "Sample email sent using nodemailer",
  html: "<h1>Hello World!</h1>"
  attachments: [
        {
            filename: 'sample_attachment.png',
            path: __dirname + '/sample_attachment.png',
        }
    ]
};

smtpTransport.sendMail(mailBody, function (error, info) {
    if (error) {
        console.log(error);
    }

    console.log("Email with attachment delivered successfully")
});

Đã xong! Rất đơn giản phải không?

Qua bài viết này, mình hi vọng bạn sẽ hiểu và có thể thực hành cách gửi mail có file đính kèm trong các dự án NodeJS.

Cùng chuyên mục:

Crawl dữ liệu website bằng NodeJS cơ bản

Crawl dữ liệu website bằng NodeJS cơ bản

CORS là gì ? Xử lý CORS trong NodeJS

CORS là gì ? Xử lý CORS trong NodeJS

Chắc hẳn trong quá trình xử lý các request tới server thì một vài trường…

Xử lý form trong Express

Xử lý form trong Express

Xây dựng URL trong Express

Xây dựng URL trong Express

Trong bài viết này chúng ta sẽ cùng nhau đi tìm hiểu về cách xây…

Populate trong Mongoose

Populate trong Mongoose

Error Handling & Debugging trong Socket.io

Error Handling & Debugging trong Socket.io

Namespaces & Rooms trong Socket.io

Namespaces & Rooms trong Socket.io

Middleware trong Mongoose

Middleware trong Mongoose

Create / Read / Update / Delete trong Mongoose

Create / Read / Update / Delete trong Mongoose

Validation trong Mongoose

Validation trong Mongoose

Subdocuments trong Mongooose

Subdocuments trong Mongooose

Documents trong Mongoose

Documents trong Mongoose

Trong bài viết này chúng ta sẽ tìm hiểu về documents trong Mongoose

Models trong Mongoose

Models trong Mongoose

SchemaTypes trong Mongoose

SchemaTypes trong Mongoose

Schemas trong Mongoose

Schemas trong Mongoose

Mongoose trong NodeJS

Mongoose trong NodeJS

Làm việc với Table MySQL sử dụng Nodejs

Làm việc với Table MySQL sử dụng Nodejs

Kết nối với MongoDB trong NodeJS

Kết nối với MongoDB trong NodeJS

Giới thiệu MongoDB trong NodeJS

Giới thiệu MongoDB trong NodeJS

Insert / Update / Delete / Select MySQL trong NodeJS

Insert / Update / Delete / Select MySQL trong NodeJS

Top