1、发送邮件模型: from smtplib import SMTP n = SMTP('smtp.yourdomain.com') ... n. quit() 2、SMTP类方法:
image.png
3、实例发送
from smtplib import SMTP as smtp
s = smtp('smtp.python.is.cool')
s.set_debuglevel(1)
s.sendmail('wesley@python.is.cool', ('wesley@python.is.cool',
'chun@python.is.cool'), ''' From: wesley@python.is.cool\r\nTo:
wesley@python.is.cool, chun@python.is.cool\r\nSubject: test
msg\r\n\r\nxxx\r\n.''')
s.quit()
3、接受邮件模型:
from poplib import POP3
p = POP3('pop.python.is.cool')
p.user(...)
p.pass_(...)
...
p. quit()
4、实例接收邮件
from poplib import POP3
p = POP3('pop.python.is.cool')
p.user('wesley')
p.pass_("you'llNeverGuess")
p.stat()
rsp, msg, siz = p.retr(102)
for eachLine in msg:
print eachLine
p.quit()
5、POP3类方法
image.png
6、完整实例,发送和接收邮件
image.png
image.png
7、IMAP4接收邮件方法
image.png
image.png
image.png
8、IMAP4例子
s = IMAP4('imap.python.is.cool') # default port: 143 s.login('wesley', 'youllneverguess') rsp, msgs = s.select('INBOX', True) rsp msgs rsp, data = s.fetch(msgs[0], '(RFC822)') rsp for line in data[0][1].splitlines()[:5]: print line s.close() s.logout() 9、发送带附件的邮件:::
image.png
解析该邮件
10、用163邮箱发送带附件的邮件: import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders
msg_from = '******@163.com' passward = '***' msg_to = '*****@qq.com'
subject = '这是测试邮件' content = '<html><body><h1>Hello</h1>' '<p>send by <a href="http://www.python.org">Python</a>...</p>' '</body></html>'
msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = msg_from msg['To'] = msg_to
msg.attach(MIMEText(content,'html','utf-8'))
with open(r'C:\1.jpg','rb') as f: mime = MIMEBase('image','jpg',filename='1.jpg') mime.add_header('Content-Disposition','attachment',filename='1.jpg') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime) try: s = smtplib.SMTP('smtp.163.com',25) s.login(msg_from,passward) s.sendmail(msg_from,msg_to,msg.as_string()) print('发送成功') except smtplib.SMTPException as e: print('发送失败' + format(e)) finally: s.quit()
//带两个附件 mime.add_header('Content-ID', '<1>') mime.add_header('X-Attachment-Id', '1')