import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

_user = "发件邮箱"
_pwd = "发件邮箱密码"
_to = "收件邮箱"

# 如名字所示Multipart就是分多个部分 # 构造一个MIMEMultipart对象代表邮件本身
msg = MIMEMultipart()
msg["Subject"] = "我的python测试邮件"
msg["From"] = _user
msg["To"] = _to

# ---这是文字部分---
part = MIMEText("我的python测试邮件的内容")
msg.attach(part)

# # ---这是附件部分---
# # xlsx类型附件
# part = MIMEApplication(open('foo.xlsx', 'rb').read())
# part.add_header('Content-Disposition', 'attachment', filename="foo.xlsx")
# msg.attach(part)
#
# jpg类型附件
part = MIMEApplication(open('foo.jpg', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename="foo.jpg")
msg.attach(part)
#
# # pdf类型附件
# part = MIMEApplication(open('foo.pdf', 'rb').read())
# part.add_header('Content-Disposition', 'attachment', filename="foo.pdf")
# msg.attach(part)
#
# # mp3类型附件
# part = MIMEApplication(open('foo.mp3', 'rb').read())
# part.add_header('Content-Disposition', 'attachment', filename="foo.mp3")
# msg.attach(part)
s = smtplib.SMTP("smtp.163.com", timeout=25) # 连接smtp邮件服务器,端口默认是25
s.login(_user, _pwd) # 登陆服务器
s.sendmail(_user, _to, msg.as_string()) # 发送邮件
s.close()


发邮件前要在邮箱设置相关的东东,百度一下,你就知道