Created
May 8, 2017 06:26
-
-
Save Everfighting/8390a710d5ed57b1aa0436e3ae90eee0 to your computer and use it in GitHub Desktop.
python邮件模块smtplib的使用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import smtplib | |
from email.mime.text import MIMEText | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.image import MIMEImage | |
from email.mime.application import MIMEApplication | |
#设置登录及服务器信息 | |
mail_host = 'smtp.163.com' | |
mail_user = '' #账号 | |
mail_pass = '' #密码(smtp服务器的密码) | |
sender = '' | |
receivers = [''] | |
#设置eamil信息 | |
#添加一个MIMEmultipart类,处理正文及附件 | |
message = MIMEMultipart() | |
message['From'] = sender | |
message['To'] = receivers[0] | |
message['Subject'] = 'title' | |
#添加一个txt文本附件 | |
with open('results.txt','r')as h: | |
content2 = h.read() | |
#设置txt参数 | |
part2 = MIMEText(content2,'plain','utf-8') | |
#附件设置内容类型,方便起见,设置为二进制流 | |
part2['Content-Type'] = 'application/octet-stream' | |
#设置附件头,添加文件名 | |
part2['Content-Disposition'] = 'attachment;filename="results.txt"' | |
#添加照片附件 | |
with open('1.jpg','rb')as fp: | |
picture = MIMEImage(fp.read()) | |
#与txt文件设置相似 | |
picture['Content-Type'] = 'application/octet-stream' | |
picture['Content-Disposition'] = 'attachment;filename="1.jpg"' | |
with open('results.xls','rb')as sh: | |
sheet = MIMEApplication(open('results.xls','rb').read()) | |
sheet.add_header('Content-Disposition', 'attachment', filename="results.xls") | |
#将内容附加到邮件主体中 | |
message.attach(part2) | |
message.attach(picture) | |
message.attach(sheet) | |
#登录并发送 | |
try: | |
smtpObj = smtplib.SMTP() | |
smtpObj.connect(mail_host,25) | |
smtpObj.login(mail_user,mail_pass) | |
smtpObj.sendmail( | |
sender,receivers,message.as_string()) | |
print('success') | |
smtpObj.quit() | |
except smtplib.SMTPException as e: | |
print('error',e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment