iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
Modern Web

30天肝出購物網站系列 第 25

Day25:25 - 優化 - 後端 - 訂單Email通知

Mholweni,我是Charlie!

在Day24當中,我們完成了訂單詳情的部分,而今天我們將回頭看一下用戶服務,寫出Email忘記密碼與Email訂單通知的後端。

================================◉‿◉=================================

首先先設定Email的部分,Email需要Google的應用程式密碼,先點選帳戶:
https://ithelp.ithome.com.tw/upload/images/20211009/20141666DZla2dXp7x.png

接著點選左欄的安全性,找到應用程式密碼:
https://ithelp.ithome.com.tw/upload/images/20211009/20141666Vz3l4a3cgW.png

如果沒有應用程式密碼的話請開啟兩步驟驗證,即可有應用程式密碼的部分。

接著點選其他,輸入要產生的應用程式密碼名稱:
https://ithelp.ithome.com.tw/upload/images/20211009/20141666uuQfmDPDjK.png

即可產生應用程式密碼的部分:
https://ithelp.ithome.com.tw/upload/images/20211009/20141666e0rF6NvjMk.png

然後到keyboardmarket\settings.py中,設定EMAIL設定檔:

#SMTP
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'Your mail'
EMAIL_HOST_PASSWORD = 'Your App password'

接著設定templates路徑:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

然後建立templates資料夾,並在裡面新增orders資料夾,並且新增createorder.html,新增訂單郵件樣板:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>建立訂單</title>
</head>
<body>
	<h1>親愛的{{ username }}您好,</h1>

	<p>感謝您在鍵盤貿易中下訂單,</p>
	<p>以下為你的訂單明細:</p>

	<table>
		<thead>
			<th>商品名稱</th>
			<th>商品價格</th>
			<th>商品數量</th>
			<th>小計</th>
		</thead>
		<tbody>
			{% for product in products %}
			    <tr>
			    	<td>{{ product.name }}</td>
			    	<td>{{ product.price }}</td>
			    	<td>{{ product.amount }}</td>
			    	<td>{% widthratio product.amount 1 product.price %}</td>
			    </tr>
			{% endfor %}
		</tbody>
	</table>

	<p>訂單編號:{{ orderno }}</p>
	<p>訂購時間:{{ created_time }}</p>
	<p>訂單狀態: {{ status }}</p>

	<p>有任何疑問歡迎洽詢鍵盤貿易客服:charlieda@keyboardmarket.org</p>
	<p>本郵件為自動發送,請勿做任何回覆。</p>
</body>
</html>

接著在tools當中建立emailClient,作為email發送的工具:

class EmailClient:
	def __init__(self):
		self.EMAIL_HOST_USER = settings.EMAIL_HOST_USER

	def send_order_message(self,
							username,
							orderno,
							products,
							created_time,
							status,
							user_email):
		email_template = render_to_string(
			'orders/createorder.html',
			{
				"username":username,
				"orderno":orderno,
				"products":products,
				"created_time":created_time,
				"status":status
			}
		)

		email = EmailMessage(
			"鍵盤貿易 - 訂單建立成功通知信",
			email_template,
			self.EMAIL_HOST_USER,
			[user_email]
		)
		email.content_subtype = 'html'
		email.fail_silently = False
		email.send()

接著我們先到shell當中做測試:
https://ithelp.ithome.com.tw/upload/images/20211009/20141666NKaKfvpaUN.png

再去收信看看,就可以看到email寄送成功囉:
https://ithelp.ithome.com.tw/upload/images/20211009/20141666VHwfcb6POd.png

接著在userorder的地方建立程式碼:

data = fromPaypalResponse(paypalresponse)
paypal_id = data["orderid"]
products = []
for cart in usercart:
	cart.status = CartStatus.deactivate.value
	cart.save()
	userorder = Order.objects.create(
		orderno = orderno,
		product = cart.product,
		user = cart.user,
		amount = cart.amount,
		status = OrderStatus.notPaid.value,
		paypal_id = paypal_id
	)	
	products.append(cart.product)

user_email = user.email
created_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
status = OrderStatus.notPaid.value

client = EmailClient()
client.send_order_message(
	user.name,
	orderno,
	products,
	created_time,
	status,
	user_email
)
return R.ok(data)

再測試就可以收到EMAIL囉。

================================◉‿◉=================================

Day25結束了!今天我們完成了Email的訂單通知,而明天我們將完成忘記密碼的功能,See ya next day!


上一篇
Day24:24 - 結帳服務(8) - 前端 - 顯示總訂單資料、訂單詳情
下一篇
Day26:26 - 優化 - 後端 & 前端 - 忘記密碼
系列文
30天肝出購物網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言