代码语言:javascript复制
#/usr/bin/env python3
# encoding: utf-8
#@author: Lejie
#@software: PyCharm Community Edition
#@file: learn_smtp.py
#@time: 2017/6/26 16:29
import smtplib
import email.mime.multipart
import email.mime.text
from email.mime.application import MIMEApplication
msg = email.mime.multipart.MIMEMultipart() #定义邮件对象
# print(msg,type(msg))
msg['from'] = 'aaaa@sobot.com' #必须和login的账号一样
msg['to'] = 'aaaa@sobot.com,bbbb@163.com'
msg['subject'] = 'test'
#邮件内容
###直接定义
content = '''
你好,
这是一封测试邮件。
'''
###从文件读取内容
content1 = open('tt.log','rb').read() #以rb来读取文件内容,可以识别中文
###插入文本
txt = email.mime.text.MIMEText(content1,'html','utf-8') #html 类型
# txt = email.mime.text.MIMEText(content1,'plain','utf-8') #txt类型
msg.attach(txt)
#文本附件 MIMEText ,这种方式文本内容会在显示在邮件内容里
# att1 = email.mime.text.MIMEText(open('tt.log', 'rb').read(), 'base64', 'utf-8')
# att1["Content-Type"] = 'application/octet-stream'
# att1["Content-Disposition"] = 'p_w_upload;filename="test.txt"'
# msg.attach(att1)
#添加附件 MIMEApplication 支持大部分图片格式,pdf,excel,mp3,txt等等
att2 = MIMEApplication(open('tt.log','rb').read())
#filename指定的名字跟实体文件名没有关系可以任意指定
att2.add_header('Content-Disposition','p_w_upload',filename="t.log")
msg.attach(att2)
#
#配置smtp
smtp = smtplib
# smtp = smtplib.SMTP() #不加密
# smtp.connect('smtp.exmail.qq.com', '25')
smtp = smtplib.SMTP_SSL() #加密
smtp.connect('smtp.exmail.qq.com', '465')
try:
#验证
smtp.login('aaaa@sobot.com', 'pass@2011')
#发送
smtp.send_message(msg) #不用指定from,to
# smtp.sendmail('aaaa@sobot.com', 'aaaa@sobot.com', str(msg)) #必须指定from,to
print("发送成功")
except Exception as e:
print(e)
smtp.quit()