# coding:utf-8
import smtplib
from email.mime.text import MIMEText # 引入smtplib和MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
host = 'smtp.126.com' # 设置发件服务器地址
port = 25 # 设置发件服务器端口号。注意,这里有SSL和非SSL两种形式
sender = '****@126.com' # 设置发件邮箱,一定要自己注册的邮箱
pwd = '****' # 设置发件邮箱的密码,等会登陆会用到,不是登录密码,是授权码
receiver = *****@163.com' # 设置邮件接收人,可以是扣扣邮箱
body = '<h1>Hi</h1><p>test</p>' # 设置邮件正文,这里是支持HTML的
"""
# 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
msg.attach(att1)
# 构造附件2,传送当前目录下的 runoob.txt 文件
att2 = MIMEText(open('runoob.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="runoob.txt"'
message.attach(att2)
"""
msg.attach(MIMEText(body, 'html')) # 设置正文为符合邮件格式的HTML内容
msg['subject'] = 'Hello world' # 设置邮件标题
att1 = MIMEText(open('D:\postgraduate-2017-2020\Data_set\GPS\BJ_BaiD_GPS_GIS.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
msg.attach(att1)
msg['from'] = sender # 设置发送人
msg['to'] = receiver # 设置接收人
try:
s = smtplib.SMTP(host, port) # 注意!如果是使用SSL端口,这里就要改为SMTP_SSL
s.login(sender, pwd) # 登陆邮箱
s.sendmail(sender, receiver, msg.as_string()) # 发送邮件!
print('Done')
except smtplib.SMTPException:
print('Error')
python 发邮件(附件)
最新推荐文章于 2024-08-21 12:14:41 发布