#!./usr/bin/env python
# -*- coding: utf-8 -*-
# Date: 2020/11/25
# Author: Jimmy
import smtplib
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email_validator import validate_email
class EmailSender(object):
"""
邮件发送客户端
"""
def __init__(self, host, user, pwd):
self.host = host # 发件服务器
self.user = user # 发件邮箱
self.pwd = pwd # 发件邮箱授权码
def __enter__(self):
"""
登录
:return:
"""
self.client = smtplib.SMTP(self.host)
self.client.login(self.user, self.pwd)
return self
def send_message(self, receiver: str, title: str, content: str):
"""
发送普通文本
:return:
"""
# 0. 验证邮箱是否有效
validate_email(receiver)
# 1. 邮件内容
msg = EmailMessage()
msg['Subject'] = title
msg['From'] = self.user
msg['To'] = receiver
msg.set_content(content)
# 2. 发送邮件
self.client.send_message(msg)
def sendmail(self, receiver: str, title: str, html: str):
"""
发送html文本
:param receiver:
:param title:
:param html:
:return:
"""
# 0. 验证邮箱是否有效
validate_email(receiver)
# 1. 邮件内容
msg = MIMEMultipart('alternative')
msg['Subject'] = title
msg['From'] = self.user
msg['To'] = receiver
msg.attach(MIMEText(html, 'html'))
# 2. 发送邮件
self.client.sendmail(self.user, receiver, msg.as_string())
def __exit__(self, exc_type, exc_val, exc_tb):
"""
退出
:param exc_type:
:param exc_val:
:param exc_tb:
:return:
"""
self.client.quit()
if __name__ == '__main__':
HOST = 'smtp.qq.com'
USER = '7905351@qq.com'
PWD = 'xxx'
text = "Hi!
How are you?
Here is the link you wanted:
http://www.python.org"
html = """
<html>
<head></head>
<body>
<h2>Hi! {name}</h2>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
with EmailSender(HOST, USER, PWD) as email_client:
# 1. 发送普通文本
email_client.send_message('7905351@gmail.com', 'Link/text', text)
# 2. 发送html文本
email_client.sendmail('7905351@gmail.com', 'Link/html', html.format(name='Jimmy'))