class MailSendingProfile(AbstractModel): """邮件发送服务器""" name = models.CharField(max_length=100, verbose_name='名称', help_text='邮件发送服务器名称') smtp_host = models.CharField(max_length=100, verbose_name='SMTP主机名', help_text='SMTP主机名请咨询邮件服务商以确定准确值。') smtp_port = models.PositiveIntegerField(default=25, verbose_name='SMTP端口', help_text='如果不启用SSL,端口号通常为25;如果启用SSL,端口号通常为465。请咨询邮件服务商以确定准确值。') username = models.EmailField(max_length=50, verbose_name='帐号', help_text='帐号') password = models.CharField(max_length=50, verbose_name='密码', help_text='密码') ssl_enabled = models.BooleanField(verbose_name='启用SSL', help_text='启用SSL') def test(self, send_to, subject, content): if not send_to: raise Exception('未指定邮箱') if not subject: subject = '测试邮件' if content.strip() == '': content = '<html><body><h1>这是一封测试邮件</h1><p>发送自意识测评系统</p></body></html>' msg = MIMEText(content, 'html', 'utf-8') msg['Subject'] = Header(subject, 'utf-8').encode() msg['From'] = self.username msg['To'] = send_to try: if self.ssl_enabled: server = smtplib.SMTP_SSL(self.smtp_host, self.smtp_port) else: server = smtplib.SMTP(self.smtp_host, self.smtp_port) except smtplib.SMTPConnectError: raise Exception('SMTP主机名格式错误') server.set_debuglevel(1) try: server.starttls() except: pass try: server.login(self.username, self.password) except smtplib.SMTPHeloError: raise Exception('向SMTP服务器发起会话失败') except smtplib.SMTPAuthenticationError: raise Exception('身份认证失败') except smtplib.SMTPException: raise Exception('服务器出现错误!请联系管理员') try: server.sendmail(str(self.username), [str(send_to)], msg.as_string()) except smtplib.SMTPHeloError: server.quit() raise Exception('向SMTP服务器发起会话失败') except smtplib.SMTPRecipientsRefused: server.quit() raise Exception('SMTP服务器拒绝收件人邮箱地址') except smtplib.SMTPSenderRefused: server.quit() raise Exception('SMTP服务器拒绝发件人邮箱地址') except smtplib.SMTPDataError: server.quit() raise Exception('SMTP服务器返回未知错误代码') server.quit() def __str__(self): return '%s (%s)' % (self.name, self.username) class Meta: verbose_name = '邮件发送服务器' verbose_name_plural = '邮件发送服务器' class SmsSendingProfile(AbstractModel): """短信网关""" name = models.CharField(max_length=100, verbose_name='名称', help_text='短信网关名称') url = models.CharField(max_length=2083, verbose_name='网关URL', help_text='网关URL') # IE limit URL length to 2083 params = models.CharField(max_length=5000, verbose_name='请求参数', help_text='请求参数') def test(self, send_to, content): if not send_to: raise Exception('未指定手机号码') if content.strip() == '': content = '【红山瑞达】这是一条测试短信,发送自意识测评系统。退订回N' context = Context({ 'to': send_to, 'content': mark_safe(content) }) resp = requests.post(self.url, data=json.loads(DjangoTemplate(self.params).render(context))) if resp.json()['status'] != 'success': raise Exception('发送测试短信失败') class Meta: verbose_name = '短信网关' verbose_name_plural = '短信网关'