import smtplib
from email import encoders
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr,formataddr
from email.header import Header
class emailUtil(object):
sender = "xxxxxx@163.com"
password = "xxxxx"
def __init__(self):
self.smtp_s = smtplib.SMTP_SSL('smtp.163.com',465)
self.smtp_s.login(self.sender,self.password)
def _format_addr(self,str):
name,addr = parseaddr(str)
return formataddr((Header(name,"utf-8").encode(),addr))
def send_text(self,to_user,content,title):
msg = MIMEText(content,"plain","utf8")
msg['Form'] = self._format_addr(self.sender)
msg['To'] = self._format_addr( to_user)
msg['Subject'] = Header(title,"utf-8").encode()
try:
self.smtp_s.sendmail(self.sender, to_user.split(','), msg.as_string())
print("邮件发送成功")
except Exception as e:
print(e)
print("邮件发送失败")
def send_image(self,to_user,title):
msg = MIMEMultipart()
msg['Form'] = self._format_addr('测试 <%s>' % self.sender)
msg['To'] = self._format_addr('管理员 <%s>' % to_user)
msg['Subject'] = Header(title, "utf-8").encode()
msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
# # 添加附件就是加上一个MIMEBase
# att1 = MIMEText(open('F:/image/1.txt', 'rb').read(), 'base64', 'utf-8')
# att1["Content-Type"] = 'application/octet-stream'
# att1["Content-Disposition"] = 'attachment; filename="new.txt"'
# msg.attach(att1)
#
# # 再添加一个图片附件
# with open('F:/image/test.png', 'rb') as f:
# att2 = MIMEBase('image', 'png', filename='test.png')
# att2.add_header('Content-Disposition', 'attachment', filename='test.png')
# att2.add_header('Content-ID', '<0>')
# att2.set_payload(f.read())
# encoders.encode_base64(att2)
# msg.attach(att2)
# fp = open('F:/image/test.png','rb')
# msg_image = MIMEImage(fp.read())
# msg_image.add_header('Content-ID','<image_1>')
# msg.attach(msg_image)
try:
self.smtp_s.sendmail(self.sender, to_user, msg.as_string())
print("邮件发送成功")
except Exception as e:
print(e)
print("邮件发送失败")
email = emailUtil()
#print(email.send_text('XXXXXX@qq.com',"内容内容","标题"));
#print(email.send_image('xxxxxx@qq.com',"标题"));
上面的路径是测试本地路径,发送html和图片时,发送不了,请大家指出问题,为什么html链接和图片发送不成功?
刚学习,请指教