话不多说,直接上代码,需要把发件里面的smtp_info替换为自己的信息,其中password是指邮箱在开通POP/SMTP功能后获取的授权码!
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders
smtp_info = {
'smtp_server': 'smtp.qq.com', # 替换为对应的邮件服务器,这是qq的,还有smtp.163.com等
'port': 465,
'sender_email': 'lytcreate@qq.com', # 替换为发件邮箱账号
'password': 'xxxxxxxxxxxxxxxx', # 替换为你自己的授权码
'receivers': ['lytcreate@163.com', 'lytcreat@163.com'] # 替换为接收人邮箱
}
def send_main(smtp_info, subject, content, img_path, excel_path):
# 设置SMTP服务器地址和端口
smtp_server = smtp_info['smtp_server']
port = smtp_info['port'] # 587:使用TLS加密, 465:SSL
# 设置发件人和收件人信息
sender_email = smtp_info['sender_email'] # 替换为你的QQ邮箱地址
password = smtp_info['password'] # 替换为你的QQ邮箱授权码
receivers = smtp_info['receivers'] # 替换为接收者的邮箱地址列表
# 创建邮件对象
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = ', '.join(receivers)
message['Subject'] = subject
mail_body = f"""
<html>
<body>
<div>{content}</div>
<img src="cid:image1" alt="Image" />
</body>
</html>
"""
message.attach(MIMEText(mail_body, 'html'))
# 添加图片到邮件正文
with open(img_path, 'rb') as f: # 替换为你的图片路径
img_data = f.read()
img = MIMEImage(img_data, name=img_path.split('/')[-1])
img.add_header('Content-ID', '<image1>') # 设置Content-ID以便在HTML中引用
message.attach(img)
# 添加Excel文件作为附件
with open(excel_path, 'rb') as f: # 替换为你的Excel文件路径
attachment = MIMEBase('application', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet')
attachment.set_payload(f.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment', filename=excel_path.split('/')[-1]) # 附件在邮件中的名称
message.attach(attachment)
# 发送邮件
try:
if port == 587:
server = smtplib.SMTP(smtp_server, port)
server.starttls() # 端口为587时启动TLS模式
else:
server = smtplib.SMTP_SSL(smtp_server, port)
server.login(sender_email, password) # 登录到你的邮箱
text = message.as_string()
server.sendmail(sender_email, receivers, text) # 发送邮件给多个接收者
print('Email sent successfully!', subject)
except Exception as e:
print(f'Failed to send email: {e}', subject)
if __name__ == '__main__':
subject = 'Python自动化测试报告' # 邮件主题
content = '这是一些测试内容' # 邮件文字内容
img_path = '123.jpg' # 邮件正文图片
excel_path = '123.xlsx' # 邮件附件excel
send_main(smtp_info, subject, content, img_path, excel_path)
发送成功效果图: