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>有任何疑问欢迎洽询键盘贸易客服:[email protected]</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!


<<:  ETA Screen (3)

>>:  Day27Java StringⅡ

Sass/Css Smacss模组化 DAY38

这里必须先介绍 为什麽我们需要模组化呢? 这里举一个例子我们尚未模组化的css //基本按钮 .bt...

Day 08-Code 要 Review,Infrastrcture 岂不 Review?吾未见其明也

Code 要 Review,Infrastrcture 岂不 Review?吾未见其明也 CI/CD...

Day 0x4 - 请求 API 前的前置动作(Part 1)[Nonce, Hash Id, Sign]

0x1 Nonce 取得 Nonce 为每次发出请求API服务前必须取得的参数之一, 而这个是需要在...

Day 30 我完成铁人了!

心得 哈罗大家,今天是铁人挑战第三十天,终於来到最後一天了,老实说我真的没想过我会参加这个比赛,更没...

Eloquent ORM - 一对一关联

Eloquent 可以在 Model 之间建立关联查询,这样可以藉由这些关联快速查询出所需的资料。 ...