반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

타닥타닥 민타쿠

Nodejs nodemailer 로 이메일 보내기(파일 첨부) 본문

개발/Nodejs

Nodejs nodemailer 로 이메일 보내기(파일 첨부)

민타쿠 2021. 8. 2. 19:26
반응형

Nodejs nodemailer 모듈로 이메일 보내는 방법

  1. npm install nodemailer (npm install nodemailer fs)
    프로젝트 경로에서 cmd 명령어로 nodemailer 모듈을 설치한다.
    (pdf 파일 첨부할 경우 fs 모듈도 함께 설치)

  2. 모듈 선언 및 transporter 생성
    const nodemailer = require('nodemailer');
    // const { readFileSync, unlinkSync, stat, readdirSync } = require('fs'); // 파일을 다룰 경우
    
    let transporter = nodemailer.createTransport({
    	// 사용하고자 하는 서비스
    	// service: 'gmail',
    	host: senderSmtp, // 'smtp.gmail.com'
    	port: senderPort, // 587
    	auth: {
    		user: senderEmail, // 'myemail@gmail.com'
    		pass: senderPass, // 'password486!'
    	}
    });​

    - 파일을 첨부할 경우 fs 모듈까지 추가로 선언한다.
    - SMTP 호스트, 포트, 발신자 이메일과 패스워드를 입력한다.
  3. 메일 보내기
    // await 을 사용하려면 async function 안에 있어야 한다.
    await transporter.sendMail({
    	// 보내는 곳의 이름과, 메일 주소를 입력
    	from: `"`+senderName+`" `+senderEmail, // `"ME" myemail@gmail.com`
    	// 받는 곳의 메일 주소를 입력
    	to: receivers, // ['one@gmail.com', 'two@gmail.com']
    	// 보내는 메일의 제목을 입력
    	subject: emailSubject, '제목입니다.'
    	// 보내는 메일의 내용을 입력
    	// text: 일반 text로 작성된 내용
    	// text: 'just test text',
    	// html: html로 작성된 내용
    	html: emailHtml, // `<p>내용입니다.</p>`
    	// 첨부파일 정보 객체를 입력
    	attachments: attachList
        // [
        //     {
    	// 	       filename: pdfFile1, // 'file1.pdf'
    	// 	       content: new Buffer(readFileSync('./pdfPath/' + pdfFile1), 'base64'), // fs 노드 모듈 사용
    	// 	       contentType: 'application/pdf'
    	//     },
        //     {
    	// 	       filename: pdfFile2, // 'file2.pdf'
    	// 	       content: new Buffer(readFileSync('./pdfPath/' + pdfFile2), 'base64'), // fs 노드 모듈 사용
    	// 	       contentType: 'application/pdf'
    	//     }
        // ]
    });​

    - 실제 메일을 전송하는 단계이다.
    - 발신자의 이름과 이메일 형식에 주의한다. (`"Name" account@gmail.com`)
    - 수신자는 리스트의 형태로 여러명에게 전송 가능하다.
    - 내용은 일반 문자로 적는 text 와 html 태그로 작성하는 html 옵션을 골라서 사용할 수 있다.
    - 첨부 파일도 여러개를 보낼 수 있지만, 용량 제한이 있다. (gmail smtp 의 경우 한 번에 총 25MB 이하만 첨부 가능)
  4. 전체 예시 코드
    const nodemailer = require('nodemailer');
    const { readFileSync, unlinkSync, stat, readdirSync } = require('fs');
    
    const pdfFolderPath = "./pdfPath/";
    
    const emailSubject = "제목입니다.";
    const emailHtml = 
    `<b>내용입니다.</b>
    <br/>
    <b>첨부된 PDF 파일들을 다운로드하세요.</b>`;
    
    // PDF 파일을 메일에 첨부하여 보낸 뒤 삭제.
    async function sendPDFMail(senderName,senderEmail,senderPass,senderSmtp,senderPort,receivers,matchedFileList){
    
    	let matchedFileList = ['one.pdf','two.pdf'];
    	// 첨부파일 리스트
    	let attachList = [];
    	for (let j = 0; j < matchedFileList.length; j++) { 
    		const matchFile = matchedFileList[j];
    		attachList.push({
    			filename: matchFile,
    			content: new Buffer(readFileSync(pdfFolderPath + matchFile), 'base64'),
    			contentType: 'application/pdf'
    		});
    	}
    
    	// 수신자에게 메일 전송
    	let transporter = nodemailer.createTransport({
    		// 사용하고자 하는 서비스
    		// service: 'gmail',
    
    		host: senderSmtp,
    		port: senderPort,
    		auth: {
    			user: senderEmail,
    			pass: senderPass,
    		}
    	});
    
    	await transporter.sendMail({
    		// 보내는 곳의 이름과, 메일 주소를 입력
    		from: `"`+senderName+`" `+senderEmail,
    		// 받는 곳의 메일 주소를 입력
    		to: receivers,
    		// 보내는 메일의 제목을 입력
    		subject: emailSubject,
    		// 보내는 메일의 내용을 입력
    		// text: 일반 text로 작성된 내용
    		// text: 'just test text',
    		// html: html로 작성된 내용
    		html: emailHtml,
    		// 첨부파일 정보 객체를 입력
    		attachments: attachList
    	});
    			
    
    	// PDF 파일 삭제
    	for (let j = 0; j < matchedFileList.length; j++) {
    		const matchFile = matchedFileList[j];
    		stat(pdfFolderPath + matchFile,(err,stat)=>{
    			if(err == null){
    				unlinkSync(pdfFolderPath + matchFile);
    				console.log('PDF deleted');
    			}else if(err.code === 'ENOENT'){
    				console.log('---Delete Error! NO PDF FILE---');
    			}else {
    				console.log('Delete error code : ' + err.code);
    			}
    		});
    	}
    }​


이해를 돕기 위한 주석과 예시 코드이다.

SMTP 메일 설정에 대해서는 되어 있다고 가정하고 따로 기록하지 않는다.

반응형
Comments