用emai和smtplib模块发email

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
import smtplib


def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))


#from_addr = input('From: ')
#password = input('Password: ')
#to_addr = input('To: ')
#smtp_server = input('SMTP server: ')
from_addr = 'b***@163.com'#'3***@qq.com'
password = '***'#'*****'
to_addr = 'b***@163.com'#'3***@qq.com'
smtp_server = 'smtp.163.com'#'smtp.qq.com'

#msg = MIMEText('hello, send by Python.', 'plain', 'utf-8')
#msg = MIMEText('<html><body><h1>Hello</h1>'+
# '<p>send by<a href="http://www.python.org">Python</a>...</p>'+
# '</body></html>','html','utf-8')

msg = MIMEMultipart()
msg['From'] = _format_addr('Python爱好者<%s>'% from_addr)
msg['To'] = _format_addr('管理员<%s>'% to_addr)
msg['Subject'] = Header('来自SMTP的问候....','utf-8').encode()

msg.attach(MIMEText('<html><body><h1>Hello</h1>'+
'<p>send by<a href="http://www.python.org">Python</a>...</p>'+
'</body></html>','html','utf-8'))


with open('/Users/lewisliu/杨.png','rb') as f:
#设置附件的MIME和文件名,这里是bmp类型
mime = MIMEBase('image','png', filename='杨.png')
#加上必要的头文件
mime.add_header('Content-Disposition', 'attachment', filename='杨.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)

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()
posted @ 2018-07-01 11:17  地瓜来了  阅读(179)  评论(0编辑  收藏  举报