# -*- coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email import encoders
from email.header import Header
from email.utils import parseaddr, formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = input('发件人:')
password = input('发件人邮箱密码:')
to_addr = input('收件人地址:')
smtp_server = input('SMTP server:')
#发送纯文本
#msg = MIMEText('hello,my name is zhangsiyang','plain','utf-8')
#发送html格式
#msg = MIMEText('<html><body><h1>Hello</h1>' +
# '<p>send by <a href="https://10.10.10.247/ovirt-engine/">eayunOS4.2</a>...</p>' +
# '</body></html>', 'html', 'utf-8')
#带附件格式的邮件
msg = MIMEMultipart()
msg['From'] = _format_addr('易云工作邮箱 <%s>' % from_addr)
msg['To'] = _format_addr('管理员 <%s>' % to_addr)
msg['Subject'] = Header('发邮件啦', 'utf-8').encode()
#msg.attach(MIMEText('发送个图片试试...', 'plain', 'utf-8'))
# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open('D:工作资料项目文档minicloud问题单云资源分配新增界面最小值可输入0.png', 'rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('image', 'png', filename='云资源分配新增界面最小值可输入0.png')
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename='云资源分配新增界面最小值可输入0.png')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
'<p><img src="cid:0"></p>' +
'</body></html>', 'html', 'utf-8'))
server = smtplib.SMTP(smtp_server,25)
server.set_debuglevel(1)
server.login(from_addr,password)
server.sendmail(from_addr,to_addr,msg.as_string())
server.quit()