码迷,mamicode.com
首页 > 移动开发 > 详细

python 异步发送邮件 aiosmtplib

时间:2019-04-13 10:51:42      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:example   tls   ror   format   log   sub   asyncio   logging   sea   

aiosmtplib is an asynchronous SMTP client for use with asyncio.项目地址
与 smtplib的用法大体相同
for example

import asyncio
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.header import Header
import aiosmtplib
import logging

def _format_addr(s): #格式化地址 也方便发送中文
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


from_addr = ''
password = ''
to_addr = ''


async def sendemail(loop):
    title = '<html><body><h3>亲爱的<a data-auto-link="1" href="mailto:%s" target="_blank">%s</a>,您好:</h3>'%(to_addr,to_addr)
    reset = "<div style = 'padding-left:55px;padding-right:55px;font-family:'微软雅黑','黑体',arial;font-size:14px;'>重置密码</div>"
    body = '<p>请点击以下链接进行重置密码 <a href="%s">%s</a></p>'%(link,reset)
    tail = '如果您并不是Awesome用户,可能是其他用户误输入了您的邮箱地址。</body></html>'
    html = title+body+tail

    msg = MIMEText(html, 'html', 'utf-8')
    msg['From'] = _format_addr('Awesome Python Webapp <%s>' % from_addr)
    msg['To'] = _format_addr('亲爱的用户 <%s>' % to_addr)
    msg['Subject'] = Header('重置密码', 'utf-8').encode()

   try:
        async with aiosmtplib.SMTP(hostname=smtp_server, port=465,use_tls=True) as smtp:
            await smtp.login(from_addr,password)
            await smtp.send_message(msg)
    except aiosmtplib.SMTPException as e:
        logging.error('sendemail:%s'%e)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(sendemail(loop))

python 异步发送邮件 aiosmtplib

标签:example   tls   ror   format   log   sub   asyncio   logging   sea   

原文地址:https://www.cnblogs.com/ShawSpring/p/10699771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!