import smtplib
import sys
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.header import Header
def _format_addr(s):
"""
地址解析 :田云 <tianyunperfect@163.com>
:param s:
:return:
"""
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
class EmailUtils(object):
def sendEmail( name, toEmail, title, content):
"""
name,email,title ,content
"""
# 设置服务器所需信息
# 163邮箱服务器地址
mail_host = 'smtp.163.com'
fromName = ""
# 163用户名
mail_user = ''
# 密码(部分邮箱为授权码)
mail_pass = ''
sslPort = '587'
# 设置email信息
# 邮件内容设置
message = MIMEText(content, 'plain', 'utf-8')
# 邮件主题
message['Subject'] = Header(title, 'utf-8').encode()
# 发送方信息
message['From'] = _format_addr('%s <%s>' % (fromName, mail_user))
# 接受方信息
message['To'] = _format_addr('%s <%s>' % (name, mail_user))
# 登录并发送邮件
try:
# 连接到服务器
smtpObj = smtplib.SMTP_SSL(mail_host, sslPort)
smtpObj.ehlo()
# 登录到服务器
smtpObj.login(mail_user, mail_pass)
# 发送
smtpObj.sendmail(
mail_user, [toEmail], message.as_string())
# 退出
smtpObj.quit()
print('send email success')
except smtplib.SMTPException as e:
print('send email error', e) # 打印错误
if __name__ == "__main__":
EmailUtils.sendEmail('177', "1777@189.cn", "待复习(10)", "点击复习")