- 邮箱常用服务器与端口
smtp.163.com 22
smtp.qq.com 465
- 开启POP3/SMTP服务
若想发送短信,则需要打开邮箱设置,并开启POP3/SMTP服务后才可发送短信,可参考下图
开启后会获得授权码,使用授权码后才能验证成功
- 话不多说,代码附上
# -*- coding: utf-8 -*-
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from pathlib import Path
class operationEmail:
def __init__(self, service: str, port: int, auth: str):
"""
:param service: 服务器
:param port: 端口
:param auth: 授权码
"""
# 创建邮件服务器对象
smt = smtplib.SMTP(host=service, port=port)
self.smt = smt
self.auth = auth
def sendEmail(self, textName: str, subject: str, sender: str, recipient: str, accessory: str):
"""
:param subject: 邮件主题
:param textName: 邮件正文
:param sender: 发送人
:param recipient: 收件人,可多个分号分隔
:param accessory: 附件地址
:return:
"""
try:
self.smt.login(sender, self.auth)
self.smt.sendmail(
sender,
recipient.split(';'),
self.__messages(textName=textName, accessory=accessory, subject=subject).as_string()
)
self.__close()
return 'Send Email succeed'
except smtplib.SMTPException as e:
self.__close()
raise ConnectionError('Connection Failure', e)
def __messages(self, textName: str, accessory: str, subject: str):
"""
创建邮箱对象
:param subject: 邮件主题
:param textName: 邮件正文
:param accessory: 邮件附件
:return:
"""
try:
m = MIMEMultipart()
m['subject'] = subject
m.attach(self.__text(textName))
m.attach(self.__accessory(accessory))
return m
except IndexError as e:
raise NameError('Create Email Error', e)
def __close(self):
"""
关闭邮箱
:return:
"""
if self.smt:
self.smt.quit()
self.smt.close()
else:
raise Exception("Email Shutdown failure")
@staticmethod
def __text(textName: str):
"""
标题
:param textName: 标题
:return:
"""
if textName:
textApart = MIMEText(textName)
return textApart
else:
raise NameError('textName Is Not Null')
@staticmethod
def __accessory(accessory: str):
"""
附件
:param accessory: 附件
:return:
"""
asyPath = accessory
if Path(asyPath).exists():
asyName = asyPath.split('\\')[-1]
asyApart = MIMEApplication(open(asyPath, mode='rb').read())
asyApart.add_header('Content-Disposition', 'attachment', filename=asyName)
return asyApart
else:
raise FileNotFoundError('File Not Found Error')
if __name__ == '__main__':
send = operationEmail(service='smtp.163.com', port=25, auth='******')
send.sendEmail(
textName='这是一份测试报告,请您认真仔细阅读',
subject='项目报告',
sender='******@163.com',
recipient='******@163.com;******@qq.com',
accessory=r'D:\test.txt'
)