1、注册163邮箱并登陆
https://mail.163.com
2、开启 IMAP/IMAP
服务
3、编写代码,进行发邮件操作(含图片发送)
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(sender_email, sender_password, receiver_email):
"""
发送邮件函数
:param sender_email: 发件人邮箱地址
:param sender_password: 授权码
:param receiver_email: 收件人邮箱地址
:return:
"""
# 创建一个带HTML内容的邮件对象
message = MIMEMultipart("alternative")
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "标题内容"
# HTML内容
html_content = f"""
<html>
<body>
<p> 正文内容 </p>
<p><img src="cid:image1" alt="image1"></p>
</body>
</html>
"""
# 将HTML内容转换为MIMEText对象
html_part = MIMEText(html_content, "html")
message.attach(html_part)
# 读取图片文件(本地图片)
with open("temp.jpg", "rb") as image_file:
# 创建一个MIMEImage对象
image = MIMEImage(image_file.read())
# 定义图片的Content-ID,用于在HTML中引用
image.add_header("Content-ID", "<image1>")
# 将图片对象添加到邮件中
message.attach(image)
# 连接到SMTP服务器
with smtplib.SMTP('smtp.163.com', 25) as server:
server.starttls() # 开启TLS加密
server.login(sender_email, sender_password) # 登录到SMTP服务器
server.send_message(message) # 发送邮件
if __name__ == '__main__':
send_mail("发件人邮箱", "授权码", "收件人邮箱")