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. Javascript继承(原始写法,非es6 class)

    知识点: Object.create的内部原理: Object.create =  function (o) {     var F = function () {};     F.prototype ...

  2. Project Euler 2 Even Fibonacci numbers

    题意:斐波那契数列中的每一项都是前两项的和.由1和2开始生成的斐波那契数列前10项为:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, -考虑该斐波那契数列中不超过四百万的项,求其 ...

  3. phpunit使用

    phpunit使用 标签(空格分隔): php 现在是凌晨 3 点.我们怎样才能知道自己的代码依然在工作呢? Web 应用程序是 24x7 不间断运行的,因此我的程序是否还在运行这个问题会在晚上一直困 ...

  4. Elasticsearch 入门 - Modifying Your Data

    index/update/delete 均有大概1秒的缓存时间 Indexing/Replacing Documents curl -X PUT "localhost:9200/custom ...

  5. vue-cli3.0 搭建项目

    1.首先我们先在安装好node   node用于npm安装[自行百度] 2.全局安装vue 通过npm命令安装vue.js 在用vue.js在用于构建大型的应用时推荐使用npm安装,npm能很好的和w ...

  6. MNIST机器学习数据集

    介绍 在学习机器学习的时候,首当其冲的就是准备一份通用的数据集,方便与其他的算法进行比较.在这里,我写了一个用于加载MNIST数据集的方法,并将其进行封装,主要用于将MNIST数据集转换成numpy. ...

  7. PHP学习总结(5)——PHP入门篇之PHP字符串

    字符串 一个字符串是用双引号括起来的一个词或一个句字,比如:"Hi,imooc!".你可以用PHP语言输出把这个字符串输出,像这样: <?php echo "Hi, ...

  8. 洛谷—— P3119 [USACO15JAN]草鉴定Grass Cownoisseur || BZOJ——T 3887: [Usaco2015 Jan]Grass Cownoisseur

    http://www.lydsy.com/JudgeOnline/problem.php?id=3887|| https://www.luogu.org/problem/show?pid=3119 D ...

  9. wifi共享精灵2014.04.25.001已经更新,wifi热点中文名走起!

    五一回来后,有个惊喜,wifi共享精灵有了最新动向.不晓得wifi共享精灵是啥的朋友,我来解释下,它就相当于一个无线路由器.说起来,Wifi共享精灵正式版2014.04.25.001(http://w ...

  10. Hadoop高速入门

    Hadoop高速入门 先决条件 支持平台 GNU/Linux是产品开发和执行的平台. Hadoop已在有2000个节点的GNU/Linux主机组成的集群系统上得到验证. Win32平台是作为开发平台支 ...