Python 发送邮件
import json from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib import constants from my_functions import get_now_time # 获取时间的方法 import osfrom configparser import ConfigParser from req import Requestclass Email(object): def __init__(self): self.user = 你的邮箱账户 self.password = 你的邮箱授权密码 self.smtp_server = smtp.163.com # 我用的163邮箱,可根据自己的邮箱进行替换 self.email_port = 465 # 邮箱端口 self.email_host_user = 发送邮件的名字 self.msg = '<p align="center" style="font-size:20px;font-weight:bold;">邮箱验证</p>' \ '<p align="center"></p>' \ '<p align="center">请点击链接验证身份信息:{0}</p><br>' \ '<p align="center">如非本人请忽略此邮件</p>' \ '<p align="center">系统邮件,请勿回复[{1}]</p>' self.msg_content = '请点击链接进行后续操作:{0}\n' # '<p align="center" style="font-size:20px;font-weight:bold;">{0}</p><br>' \ # print('send_email(from_addr,password,to_addr,smtp_server,mimetext,msg_from,msg_to,msg_subject)') def format_addr(self, s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) def send_email(self, to_addr='收件箱账户', msg_from='发件人称呼', msg_to='收件人称呼', msg_subject=None, code='000000'):
# 发送邮件 msg = MIMEText(self.msg.format(code, get_now_time()), 'html', 'utf-8') msg['From'] = self.format_addr(msg_from + ' ' + '<%s>' % self.user) msg['To'] = self.format_addr(msg_to + ' ' + '<%s>' % to_addr) msg['Subject'] = Header(msg_subject, 'utf-8').encode() server = smtplib.SMTP_SSL(self.smtp_server, self.email_port, timeout=15) server.login(self.user, self.password) server.sendmail(self.user, [to_addr], msg.as_string()) server.quit() def email_message(self, to_addr='收件箱账户', msg_from='发件人称呼', msg_to='收件人称呼', msg_subject=None, msg=''):
# 发送提醒邮件 self.msg = '<p style="font-size:20px;font-weight:bold;">消息通知</p>' \ '<p>{0}</p>' \ '<p>系统邮件,请勿回复</p>' msg = MIMEText(self.msg.format(msg), 'html', 'utf-8') msg['From'] = self.format_addr(msg_from + ' ' + '<%s>' % self.user) msg['To'] = self.format_addr(msg_to + ' ' + '<%s>' % to_addr) msg['Subject'] = Header(msg_subject, 'utf-8').encode() server = smtplib.SMTP_SSL(self.smtp_server, self.email_port, timeout=15) server.login(self.user, self.password) server.sendmail(self.user, to_addr, msg.as_string()) server.quit()
if __name__ == '__main__': eml = Email() eml_result = eml.send_email(参数)
print(eml_result)