import smtplib
from email.mime.text import MIMEText
from email.header import Header
class SendEmail():
def __init__(self,sender="",smtpserver='smtp.163.com',
username ="",
password=""):
self.sender =sender
self.smtp = smtplib.SMTP()
self.smtp.connect(smtpserver)
self.smtp.login( username,password)
def send(self,email_data):
if not isinstance(email_data,dict):
raise TypeError("EMAIL DATA MUST BY DICT ")
msg = MIMEText(email_data["Text"], 'plain', 'utf-8') # 中文需参数‘utf-8',单字节字符不需要
msg['Subject'] = Header(email_data["Subject"], 'utf-8')
msg['From'] = email_data["From"]
msg['To'] = email_data["To"]
self.smtp.sendmail(self.sender,email_data["To"] , msg.as_string())
def __del__(self):
self.smtp.close()
def test_send_email():
email_data = {"Text":"test send emain","Subject":"test","From":"","To":""}
se = SendEmail()
se.send(email_data)
if __name__ == '__main__':
test_send_email()
其中:
sender :163邮箱地址
username:邮箱smtp用户名(默认为邮箱地址)
password: 开通smtp服务时显示的密码
msg["Subject"]:发送邮件的主题
msg["Text"]:发送邮件的正文
msg["From"]: 表明邮件发送地址 ,格式为:Tim<******@163.com>
msg["To"]:邮件接受地址