1、文件结构:
-message
-__init__.py
-base.py
-dingding.py
-email.py
-msg.py
-wx.py
2、配置文件(以Django配置为例)
MESSAGE_CLASSES = [ 'utils.message.email.Email', 'utils.message.msg.Msg', 'utils.message.wx.WeChat', 'utils.message.dingding.DingDing', ] #根目录下有个utils文件夹,message文件夹放在该目录下
3、文件内容
__init__.py
import importlib from django.conf import settings def send_message(to,name,subject,body): """ 短信、邮件、微信 :param to: 接受者 :param name: 接受者姓名 :param subject: 主题 :param body: 内容 :return: """ for cls_path in settings.MESSAGE_CLASSES: # cls_path是字符串 module_path,class_name = cls_path.rsplit('.',maxsplit=1) m = importlib.import_module(module_path) obj = getattr(m,class_name)() obj.send(subject,body,to,name,)
base.py
class BaseMessage(object): def send(self, subject, body, to, name): raise NotImplementedError('未实现send方法')
dingding.py
from .base import BaseMessage class DingDing(BaseMessage): def __init__(self): pass def send(self,subject,body,to,name): print('钉钉消息发送成功')
email.py
#!/usr/bin/env python # -*- coding:utf-8 -*- import smtplib from email.mime.text import MIMEText from email.utils import formataddr from .base import BaseMessage class Email(BaseMessage): def __init__(self): self.email = "your email" self.user = "your nickname" self.pwd = 'your email password' def send(self,subject,body,to,name): msg = MIMEText(body, 'plain', 'utf-8') # 发送内容 msg['From'] = formataddr([self.user,self.email]) # 发件人 msg['To'] = formataddr([name, to]) # 收件人 msg['Subject'] = subject # 主题 server = smtplib.SMTP("SMTP服务", 25) # SMTP服务 server.login(self.email, self.pwd) # 邮箱用户名和密码 server.sendmail(self.email, [to, ], msg.as_string()) # 发送者和接收者 server.quit()
msg.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from .base import BaseMessage class Msg(BaseMessage): def __init__(self): pass def send(self,subject,body,to,name): print('短信发送成功')
wx.py
from .base import BaseMessage class WeChat(BaseMessage): def __init__(self): pass def send(self,subject,body,to,name): print('微信发送成功')