當我們創建一個網站時,經常會有發送郵件的需要。無論是用戶注冊,還是用戶忘記密碼,又或者是用戶下單后進行付款確認,都需要發
送不同的郵件。所以發送郵件的需求實際上是非常重要的,而且如果如果不在一開始就建造結構清晰的郵件服務,到后面可能會是一團糟。
基本的郵件發送
假設我們希望在用戶注冊到我們的網站。我們可以參照Django文檔,向驗證通過并創建成功的用戶發送郵件。具體實現如下:
import logging from rest_framework.views import APIView from django.http import JsonResponse from django.core.mail import send_mail from users.models import User logger = logging.getLogger('django') class RegisterView(APIView): def post(self, request): # Run validations if not request.data: return JsonResponse({'errors': 'User data must be provided'}, status=400) if User.objects.filter(email=request.data['email']).exists(): return JsonResponse({'errors': 'Email already in use'}, status=400) try: # Create new user user = User.objects.create_user(email=request.data['email'].lower()) user.set_password(request.data['password']) user.save() # Send welcome email send_mail( subject='Welcome!', message='Hey there! Welcome to our platform.', html_message='<p><strong>Het there!</strong> Welcome to our platform.</p>' from_email='from@example.com', recipient_list=[user.email], fail_silently=False, ) return JsonResponse({'status': 'ok'}) except Exception as e: logger.error('Error at %s', 'register view', exc_info=e) return JsonResponse({'errors': 'Wrong data provided'}, status=400)
當然肯定文檔中所說的那樣,你也必須提前設定好一些重要的配置項,例如EMAIL_HOST和EMAIL_PORT。
很好!現在我們已經發送了歡迎郵件!
創建一個mailer類
正如我之前所說,在我們的應用中不同的模塊可能都需要發送郵件,所以最好有一個電子郵件服務或者mailer類來處理所有的郵件請求。更簡單,因為我們不再需要每次都去翻遍全部代碼。
iimport logging from django.conf import settings from django.core.mail import send_mail from users.models import User logger = logging.getLogger('django') class BaseMailer(): def __init__(self, to_email, subject, message, html_message): self.to_email = to_email self.subject = subject self.message = message self.html_message = html_message def send_email(self): send_mail( subject=self.subject, message=self.message, html_message=self.html_message, from_email='from@example.com', recipient_list=[self.to_email], fail_silently=False, )
讓我們來看看經過這次改變后,注冊服務的視圖層是某種子:
import logging from rest_framework.views import APIView from django.http import JsonResponse from django.core.mail import send_mail from users.models import User from users.mailers import BasicMailer logger = logging.getLogger('django') class RegisterView(APIView): def post(self, request): # Run validations if not request.data: return JsonResponse({'errors': 'User data must be provided'}, status=400) if User.objects.filter(email=request.data['email']).exists(): return JsonResponse({'errors': 'Email already in use'}, status=400) try: # Create new user user = User.objects.create_user(email=request.data['email'].lower()) user.set_password(request.data['password']) user.save() # Send welcome email BasicMailer(to_email=user.email, subject='Welcome!', message='Hey there! Welcome to our platform.', html_message='<p><strong>Het there!</strong> Welcome to our platform.</p>').send_email() return JsonResponse({'status': 'ok'}) except Exception as e: logger.error('Error at %s', 'register view', exc_info=e) return JsonResponse({'errors': 'Wrong data provided'}, status=400) 作者:cyril_lee 鏈接:https://juejin.im/post/5eb6171c5188256d7a3cac97 來源:掘金 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
mailer子類
現在我們已經把所有的“郵件代碼”移動到一個單獨的地方,可以把它利用起來啦!這時候可以繼續創建特定的mailer類,并讓它們知道每次被調用時該發送什么內容。讓我們創建一個mailer類用來在每次用戶注冊時進行調用,另一個mailer類用來發送訂單的確認信息。
import logging from django.conf import settings from django.core.mail import send_mail from users.models import User logger = logging.getLogger('django') class BaseMailer(): def __init__(self, to_email, subject, message, html_message): self.to_email = to_email self.subject = subject self.message = message self.html_message = html_message def send_email(self): send_mail( subject=self.subject, message=self.message, html_message=self.html_message, from_email='from@example.com', recipient_list=[self.to_email], fail_silently=False, ) class RegisterMailer(BaseMailer): def __init__(self, to_email): super().__init__(to_email, subject='Welcome!', message='Hey there! Welcome to our platform.', html_message='<p><strong>Het there!</strong> Welcome to our platform.</p>') class NewOrderMailer(BaseMailer): def __init__(self, to_email): super().__init__(to_email, subject='New Order', message='You have just created a new order', html_message='<p>You have just created a new order.</p>')
這表明在不同的場景下集成郵件服務是非常簡單的。你只需要構造一個基礎的郵件類來進行實現,然后在子類中設置具體內容。
因為不用實現所有郵件相關的代碼,所以現在我們注冊服務的視圖層看起來更加簡明:
import logging from rest_framework.views import APIView from django.http import JsonResponse from django.core.mail import send_mail from users.models import User from users.mailers import RegisterMailer logger = logging.getLogger('django') class RegisterView(APIView): def post(self, request): # Run validations if not request.data: return JsonResponse({'errors': 'User data must be provided'}, status=400) if User.objects.filter(email=request.data['email']).exists(): return JsonResponse({'errors': 'Email already in use'}, status=400) try: # Create new user user = User.objects.create_user(email=request.data['email'].lower()) user.set_password(request.data['password']) user.save() # Send welcome email RegisterMailer(to_email=user.email).send_email() return JsonResponse({'status': 'ok'}) except Exception as e: logger.error('Error at %s', 'register view', exc_info=e) return JsonResponse({'errors': 'Wrong data provided'}, status=400)
使用Sendgrid
假設我們必須使用正式的蟒庫將我們的郵件服務后端遷移Sendgrid(一個用于交易和營銷郵件的客戶通信平臺)。我們將不能再使用的Django的SEND_EMAIL方法,而且我們還不得不使用新庫的語法。
嗯,但我們還是很幸運的地方!因為我們已經將所有與郵件管理相關的代碼都放到了一個單獨的地方,所以我們可以很輕松的進行這場比賽
import logging from django.conf import settings from sendgrid import SendGridAPIClient, Email, Personalization from sendgrid.helpers.mail import Mail from users.models import User logger = logging.getLogger('django') class BaseMailer(): def __init__(self, email, subject, template_id): self.mail = Mail() self.subject = subject self.template_id = template_id def create_email(self): self.mail.from_email = Email(settings.FROM_EMAIL) self.mail.subject = self.subject self.mail.template_id = self.template_id personalization = Personalization() personalization.add_to(Email(self.user.email)) self.mail.add_personalization(personalization) def send_email(self): self.create_email() try: sg = SendGridAPIClient(settings.SENDGRID_API_KEY) sg.send(self.mail) except Exception as e: logger.error('Error at %s', 'mailer', exc_info=e) class RegisterMailer(BaseMailer): def __init__(self, to_email): super().__init__(to_email, subject='Welcome!', template_id=1234) class NewOrderMailer(BaseMailer): def __init__(self, to_email): super().__init__(to_email, subject='New Order', template_id=5678)
請注意,您必須在配置文件中設置Sendgrid的api密鑰,以及指定需要被使用的模板的ID,Sendrid會直接從自己的頁面中根據這個ID來加載指定的html郵件模版。
太好了!這并不困難,而且我們不用去修改發送郵件的每一行代碼。
現在讓我們的步子再邁大一點。
根據域信息定制郵件內容
當然我們發送郵件的時候,有時候可能也會使用一些域信息來填充模板。比如說,如果在歡迎郵件里面能有新用戶的名字,那肯定會顯得更友好。Sendgrid 允許你在郵件模板中定義變量,這些變量將替換為從我們這里接收的實際信息。所以現在讓我們來添加這部分數據吧!
import logging from django.conf import settings from sendgrid import SendGridAPIClient, Email, Personalization from sendgrid.helpers.mail import Mail from users.models import User logger = logging.getLogger('django') class BaseMailer(): def __init__(self, email, subject, template_id): self.mail = Mail() self.user = User.objects.get(email=email) self.subject = subject self.template_id = template_id self.substitutions = { 'user_name': self.user.first_name, 'user_surname': self.user.last_name } def create_email(self): self.mail.from_email = Email(settings.FROM_EMAIL) self.mail.subject = self.subject self.mail.template_id = self.template_id personalization = Personalization() personalization.add_to(Email(self.user.email)) personalization.dynamic_template_data = self.substitutions self.mail.add_personalization(personalization) def send_email(self): self.create_email() try: sg = SendGridAPIClient(settings.SENDGRID_API_KEY) sg.send(self.mail) except Exception as e: logger.error('Error at %s', 'mailer', exc_info=e) class RegisterMailer(BaseMailer): def __init__(self, to_email): super().__init__(to_email, subject='Welcome!', template_id=1234) class NewOrderMailer(BaseMailer): def __init__(self, to_email): super().__init__(to_email, subject='New Order', template_id=5678)
這里我看到的唯一一個問題是替換方案不那么靈活。很可能會發生的情況是,我們傳遞的數據可能是用戶根據請求的上下文訪問不到的。比如說,新的訂單編號、重置密碼的鏈接等等。這些變量參數可能很多,把它們作為命名參數傳遞可能會讓代碼變得比較臟亂。我們希望的是一個基于關鍵字,并且長度可變的參數列表,一般來說會被定義為 **kwargs,但在此我們命名它為 **substitutions,讓這個表達會更形象:
import loggingfrom django.conf import settingsfrom sendgrid import SendGridAPIClient, Email, Personalizationfrom sendgrid.helpers.mail import Mailfrom users.models import User logger = logging.getLogger('django')class BaseMailer(): def __init__(self, email, subject, template_id, **substitutions): self.mail = Mail() self.user = User.objects.get(email=email) self.subject = subject self.template_id = template_id self.substitutions = { 'user_name': self.user.first_name, 'user_surname': self.user.last_name } for key in substitutions: self.substitutions.update({key: substitutions[key]}) def create_email(self): self.mail.from_email = Email(settings.FROM_EMAIL) self.mail.subject = self.subject self.mail.template_id = self.template_id personalization = Personalization() personalization.add_to(Email(self.user.email)) personalization.dynamic_template_data = self.substitutions self.mail.add_personalization(personalization) def send_email(self): self.create_email() try: sg = SendGridAPIClient(settings.SENDGRID_API_KEY) sg.send(self.mail) except Exception as e: logger.error('Error at %s', 'mailer', exc_info=e) class RegisterMailer(BaseMailer): def __init__(self, to_email, **substitutions): super().__init__(to_email, subject='Welcome!', template_id=1234, **substitutions) class NewOrderMailer(BaseMailer): def __init__(self, to_email): super().__init__(to_email, subject='New Order', template_id=5678, **substitutions)
如果希望將額外信息傳遞給 mailer 類,就需要按如下編碼:
NewOrderMailer(user.email, order_id=instance.id).send_email() PasswordResetMailer(user.email, key=password_token.key).send_email()