import os
import asyncio
import logging
import base64
from email import message_from_bytes
from email.message import Message
from datetime import datetime import aiosmtpd
from aiosmtpd.controller import Controller
from aiosmtpd.smtp import SMTP as Server, syntax
from jinja2 import Template mail_path = "mails"
hostname = "0.0.0.0"
port = 8025 html = """\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>email</title>
</head>
<body>
<div><span>发件人: </span><span>{{ from_addr|e }}</span></div>
<div><span>收件人: </span><span>{{ to_addr|e }}</span></div>
<div><span>主题: </span><span>{{ subject }}</span></div>
<div>
{{ payload }}
</div>
</body>
</html>
""" class ExampleHandler:
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
envelope.rcpt_tos.append(address)
return "250 OK" async def handle_DATA(self, server, session, envelope: aiosmtpd.smtp.Envelope):
message: Message = message_from_bytes(envelope.content)
message_info = await self.parse_message(message)
template = Template(html)
if not os.path.exists(mail_path):
os.makedirs(mail_path)
with open(os.path.join(mail_path, f"mail_{datetime.now().strftime('%Y-%m-%d-%H_%M_%S_%f')[:-3]}.html"), "w") as f:
f.write(template.render(message_info))
return "250 Message accepted for delivery" def get(self, message, item):
value = message.get(item)
try:
value = self.to_true_str(value)
except Exception:
pass
return value async def parse_message(self, message: Message):
self.charset = message.get_content_charset() or "utf-8"
payload = message.get_payload()
subject = self.get(message, "Subject")
from_addr = self.get(message, "From")
to_addr = self.get(message, "To")
try:
if isinstance(payload, (list, tuple)):
payload = self.parse_payload(payload)
except Exception:
pass
return {"subject": subject, "payload": payload, "from_addr": from_addr, "to_addr": to_addr} def parse_payload(self, payload):
# todo 暂时不处理附件的问题,目前仅处理 text/html 与 text/plain 共存的情况
data = None
for item in payload:
if isinstance(item, Message):
data = item.get_payload()
if item.get_content_type == "text/html":
break try:
# 测试发现 html 有概率是转 base64
data = self.to_true_str(data)
except Exception:
pass return data def to_true_str(self, raw: str, charset=None):
if raw.startswith("=?"):
tmp_list = raw.split("?")
if len(tmp_list) > 2:
raw = tmp_list[-2]
charset = tmp_list[1]
else:
charset = self.charset
return base64.b64decode(raw).decode(charset) async def handle_EHLO(self, *args, **kwargs):
return """\
250-mail
250-PIPELINING
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-coremail
250-STARTTLS
250-SMTPUTF8
250 8BITMIME""" class MyServer(Server): @syntax("AUTH PLAIN")
@asyncio.coroutine
def smtp_AUTH(self, PLAIN, *args, **kwargs):
yield from self.push("235 auth successfully") @syntax("EHLO hostname")
async def smtp_EHLO(self, hostname):
status = await self._call_handler_hook("EHLO", hostname)
self.session.host_name = hostname
await self.push(status) class MyController(Controller):
def factory(self):
return MyServer(self.handler) async def amain(loop):
controller = MyController(ExampleHandler(), hostname=hostname, port=port)
controller.start() if __name__ == "__main__":
logging.basicConfig(level=logging.ERROR)
loop = asyncio.get_event_loop()
loop.create_task(amain(loop=loop))
try:
loop.run_forever()
except KeyboardInterrupt:
pass

faker smtp server的更多相关文章

  1. SSRS1:配置SMTP Server发送mail

    为了使用SSRS发送mail,必须为Reporting service配置SMTP Server. 1,在Reporting Service Configuration Manager中配置Email ...

  2. Spring – Sending E-Mail Via Gmail SMTP Server With MailSender--reference

    Spring comes with a useful ‘org.springframework.mail.javamail.JavaMailSenderImpl‘ class to simplify ...

  3. Check SMTP Server Availability for ORA-29278 or ORA-29279 errors using UTL_SMTP to Send Email

    Check SMTP Server Availability for ORA-29278 or ORA-29279 errors using UTL_SMTP to Send Email. (文档 I ...

  4. phpmailer的SMTP ERROR: Failed to connect to server: 10

    请问,我在win7上学习使用phpmailer时,出现这种错误怎么处理啊? SMTP ERROR: Failed to connect to server: (0) SMTP connect() fa ...

  5. Reporting Service 配置SMTP和设置订阅出现的异常

    SSRS能够按照schedule,以mail的形式发送report,这是通过设置subscription report来实现的. 1,发送mail需要在SSRS中配置SMTP Server,如果没有R ...

  6. P6 Professional Installation and Configuration Guide (Microsoft SQL Server Database) 16 R1

    P6 Professional Installation and Configuration Guide (Microsoft SQL Server Database) 16 R1       May ...

  7. How to Use Telnet to Test SMTP Communication

    Topic Last Modified: 2005-05-24 Telnet is an extremely useful tool for troubleshooting issues relate ...

  8. 在CI中集成phpmailer,方便使用SMTP发送邮件

    直接使用phpmailer的话,有时候不是很方便,特别你的很多功能都是基于CI完成的时候,要相互依赖就不方便了,所以在想,那是否可以将phpmailer集成到CI中呢,像使用email类这样使用他,功 ...

  9. Understanding and Managing SMTP Virtual Servers

    Simple Mail Transfer Protocol (SMTP) Service Overview The Simple Mail Transfer Protocol (SMTP) servi ...

随机推荐

  1. 编译qemu

    el7上编译 git clone git://git.qemu-project.org/qemu.git ./configure --target-list=x86_64-softmmu --cpu= ...

  2. 原生node实现简易留言板

    原生node实现简易留言板 学习node,实现一个简单的留言板小demo 1. 使用模块 http模块 创建服务 fs模块 操作读取文件 url模块 便于path操作并读取表单提交数据 art-tem ...

  3. 洛谷 P1567 统计天数

    题目背景 统计天数 题目描述 炎热的夏日,KC非常的不爽.他宁可忍受北极的寒冷,也不愿忍受厦门的夏天.最近,他开始研究天气的变化.他希望用研究的结果预测未来的天气. 经历千辛万苦,他收集了连续N(1& ...

  4. useradd常用参数介绍

    -c :新账号passwd档的说明栏 -d :新账号每次登录时所使用的home_dir,预设值为default_home内login名称,并当成登录时目录名称 -e :*账号终止日期,日期的指定格式为 ...

  5. CF369E. ZS and The Birthday Paradox

    /* cf369E. ZS and The Birthday Paradox http://codeforces.com/contest/711/problem/E 抽屉原理+快速幂+逆元+勒让德定理 ...

  6. 判断webservice是否可用

    在.net中验证WebService的Url有效并且验证服务可用: 需要用到win32下的组件,比如Microsoft XML, v5.0 测试程序具体如下:建一个项目,在你的引用中添加COM---找 ...

  7. BA-siemens-BA模块特性

    PXC24(包含UEC24的模块特性) DO点可以接220vac的电压,渠道人员告知电流不要超过2A AO点只能输出0-10V的电压,不能输出4-20ma的电流,说明书上是错误的 AO点输出10v失败 ...

  8. 计算机网络系统--TCP/IP OSI模型

  9. java import跨包引用类理解

    当前类要用其他类时,import具体包路径+.+具体的类 import引入的是被引用类的class文件,所以当我们build path第三方jar包时, 要用他们的类,要把jar包add to bui ...

  10. HDU 4228

    很明显可以转化为反素数的题目.由于有n种不同的方式,所以,数的约数可以为2*n或者2*n-1 #include <iostream> #include <cstdio> #in ...