본문 바로가기
웹 개발 실습/Django

[Django]_맛집 공유 사이트 만들기 (3) 이메일 보내기

by ssolLEE 2023. 7. 31.
반응형

 

이 프로젝트도 마찬가지로 책 'Django 한 그릇 뚝딱'의 Chapter 3을 보며 실행해보았습니다. 책의 저자님께 다시 한 번 감사말씀 드립니다.

 

 

 

이번 시간에는 '이메일 보내기' 기능을 구현해보겠습니다. 

이를 위해서는 먼저 구글 계정이 필요합니다. 

  • RestaurantShare> shareRes > templates > shareRes > index.html로 이동합니다.
  • 다음과 같이 <form>태그의 action값을 채워줍니다.

  • RestaurantShare> sendEmail > views.py로 이동하여 코드를 수정합니다.

  • index.html의 227번째 줄을 보면 맛집들의 체크박스의 이름은 checks로 동일하다는 것을 알 수 있습니다. djang는 이름을 동일하게 했을 때 체크된 요소들만 그 value값을을 받아 올 수 있기 떄문에 이렇게 설정한 것입니다.

 

사용자가 선택한 맛집 및 입력한 내용 받아오기

  • RestaurantShare> sendEmail > views.py로 이동하여 코드를 수정합니다.
def sendEmail(request):
    checked_res_list = request.POST.getlist('checks')
    inputReceiver = request.POST['inputReceiver']
    inputTitle = request.POST['inputTitle']
    inputContent = request.POST['inputContent']
    print(checked_res_list,"/", inputReceiver, "/", inputTitle, "/", inputContent)
    return HttpResponseRedirect(reverse('index'))
    # return HttpResponse("sendEmail")
  • 웹 페이지를 새로고침하고 '이메일 발송하기'를 클릭하면 다음과 같이 terminal창에 출력됩니다.

 

 

사용자가 선택한 맛집과 인사말을 이용해 이메일 본문 작성하기

  • RestaurantShare> sendEmail > views.py로 이동하여 코드를 입력합니다. (이메일 본문 작성)
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from shareRes.models import *
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Create your views here.
def sendEmail(request):
    checked_res_list = request.POST.getlist('checks')
    inputReceiver = request.POST['inputReceiver']
    inputTitle = request.POST['inputTitle']
    inputContent = request.POST['inputContent']

    mail_html = "<html><body>"
    mail_html += "<h1> 맛집 공유 </h1>"
    mail_html += "<p>" +inputContent+"<br>"
    mail_html += "발신자님께서 공유하신 맛집은 다음과 같습니다.</p>"
    for checked_res_id in checked_res_id:
        restaurant = Restaurant.objects.get(id = checked_res_id)
        mail_html += "<h2>" +restaurant.restaurant_name+"</h3>"
        mail_html += "<h4>* 관련 링크</h4>" + "<p>" +restaurant.restaurant_link+"</p><br>"
        mail_html += "<h4>* 상세 내용</h4>" + "<p>" +restaurant.restaurant_content+"</p><br>"
        mail_html += "<h4>* 관련 키워트</h4>" + "<p>" +restaurant.restaurant_keyword+"</p><br>"
        mail_html += "<br>"
    mail_html +="</body></html>"
    # print(checked_res_list,"/", inputReceiver, "/", inputTitle, "/", inputContent)
    return HttpResponseRedirect(reverse('index'))
    # return HttpResponse("sendEmail")
  • 위와 같이 구성한 이메일 본문에 대해서 사용자가 입력한 수신자와 이메일 제목으로 이메일 발송을 해보겠습니다. 

 

Google 2단계 인증 후 앱 비밀 번호 부여받기

 

이메일 발송 코드 구현하기

 

  • RestaurantShare> sendEmail > views.py로 이동하여 코드를 입력합니다. 
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from shareRes.models import *
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Create your views here.
def sendEmail(request):
    checked_res_list = request.POST.getlist('checks')
    inputReceiver = request.POST['inputReceiver']
    inputTitle = request.POST['inputTitle']
    inputContent = request.POST['inputContent']

    mail_html = "<html><body>"
    mail_html += "<h1> 맛집 공유 </h1>"
    mail_html += "<p>" +inputContent+"<br>"
    mail_html += "발신자님께서 공유하신 맛집은 다음과 같습니다.</p>"
    for checked_res_id in checked_res_id:
        restaurant = Restaurant.objects.get(id = checked_res_id)
        mail_html += "<h2>" +restaurant.restaurant_name+"</h3>"
        mail_html += "<h4>* 관련 링크</h4>" + "<p>" +restaurant.restaurant_link+"</p><br>"
        mail_html += "<h4>* 상세 내용</h4>" + "<p>" +restaurant.restaurant_content+"</p><br>"
        mail_html += "<h4>* 관련 키워트</h4>" + "<p>" +restaurant.restaurant_keyword+"</p><br>"
        mail_html += "<br>"
    mail_html +="</body></html>"
    # print(checked_res_list,"/", inputReceiver, "/", inputTitle, "/", inputContent)

    # smtp using
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.login("djangoemailtester001@gmail.com", "tester001") # 자신의 구글메일, 앱 비밀번호 입력

    msg = MIMEMultipart('alternative')
    msg['Subject'] = inputTitle
    msg['From'] = "djangoemailtester--1@gmail.com"
    msg['To'] = inputReceiver
    mail_html = MIMEText(mail_html, 'html')
    msg.attach(mail_html)
    print(msg['To'], type(msg['To']))
    server.sendmail(msg['From'], msg['To'].split(','), msg.as_string())
    server.quit()

    return HttpResponseRedirect(reverse('index'))
    # return HttpResponse("sendEmail")
  • 이메일 발송하기를 해보면 다음과 같이 메일이 발송됩니다. 

지금까지 너무나도 기나긴 맛집 공유 사이트 만들기, 정말 수고 많으셨습니다.

감사합니다.