day10_发送带附件的邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart # 发送附件导入MIMEMultipart
# username = 'sunshujiang184@163.com'
username = '174596537@qq.com'
# email_host = 'smtp.163.com'
email_host = 'smtp.qq.com'# qq邮箱里要设置一下,设置->账户,开启POP3/SMTP服务,发送短信获取授权码
passwd = 'gqeiozxjoojqcabf' # 用qq邮箱发送邮件也要使用授权码
# recv = ['511402865@qq.com',]
# recv = '511402865@qq.com'
recv = 'sunshujiang184@163.com'
title = 'I love you哈哈'# 邮件标题
content = 'I love you too'# 邮件正文
msg = MIMEMultipart()# 构造一个邮件内容的对象
file = 'a.txt'# 当前目录下要有这个文件
att = MIMEText(open(file,encoding = 'utf8').read()) # 发送的附件对象
att["Content-Type"] = 'application/octet-stream' # 发送的文件类型
att["Content-Disposition"] = 'attachment; filename = "%s"' % file # 发送的附件
msg.attach(att) # 把附件添加到邮件里面
msg.attach(MIMEText(content)) # 邮件正文内容添加到msg邮件对象里面
msg['Subject'] = title # 邮件标题
msg['From'] = username # 发邮件人
msg['To'] = recv # 接收邮件人
smtp = smtplib.SMTP_SSL(email_host,port = 465) # 发邮件的邮箱是qq邮箱时,用这个
# smtp = smtplib.SMTP(email_host,port = 25) # 其他邮箱
smtp.login(username,passwd)
smtp.sendmail(username,recv,msg.as_string())
smtp.quit()
print ('email send success.')












posted @ 2018-03-18 22:30  laosun0204  阅读(106)  评论(0编辑  收藏  举报